React state is empty after setting

Viewed 95

I have simple nextjs app where i want to save and print state to fetchData

This is my code

const Room = () => {
  const router = useRouter();
  const [fetchData, setFetchData] = useState("");

  useEffect(() => {
    if (router.asPath !== router.route) {
      getDataNames();
      console.log(fetchData); // Empty
    }
  }, [router]);

  const getDataNames = async () => {
    try {
      await fetch("http://localhost:1337/rooms?_id=" + router.query.id)
        .then((response) => response.json())
        .then((jsonData) => setFetchData(jsonData) & console.log(jsonData)); // Data are logged in console
    } catch (e) {
      console.error(e);
    }
  };

Problem is that fetchData is empty on console log but jsonData gaves me actual data. And i have no idea what can be problem.

2 Answers

Ok so 3 things here. Firstly, your useEffect doesn't re-run when your fetchData value changes. You need to add it to the dependency list:

  useEffect(() => {
    if (router.asPath !== router.route) {
      getDataNames();
      console.log(fetchData); // Empty
    }
  }, [router, fetchData]);

this way the effect will run when fetchData changes. And of course it will only console.log it if that condition inside the effect's if condition is satisfied.

Secondly, you're mixing async/await and .then/.catch syntax, don't do that. Use one or the other. In this case you can just remove the await keyword and try/catch block, and use your existing .then code, and add a .catch to it to catch any errors.

Finally, & in Javascript is the bitwise AND operator, so not sure why you were using it there. If you think it means "and also do this", then that's incorrect. Just put the .then function inside curly braces and call the setFetchData and console.log statements one after the other:

.then((jsonData) => {
    setFetchData(jsonData);
    console.log(jsonData)
});
 useEffect(() => {

      console.log(fetchData);
    
  }, [fetchData]);

use this hook to log your data

Related