Michaelo
Michaelo

Reputation: 839

React state is empty after setting

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.

Upvotes: 2

Views: 741

Answers (2)

Jayce444
Jayce444

Reputation: 9063

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)
});

Upvotes: 1

Anh Tuan
Anh Tuan

Reputation: 1143

 useEffect(() => {

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

use this hook to log your data

Upvotes: 1

Related Questions