-1

I have the following function that refreshes my states

const refreshAfterCreate = async () => {
      try {
        const res = await fetch(process.env.NEXT_PUBLIC_MICROSERVICE_COMPANY_URL + '/companies',         {method: 'GET'});
        const data = await res.json();
        await setCompanies(data);
      } catch (error) {
        console.error('Error al realizar el fetch:', error);
      }
      try {
        const res = await fetch(process.env.NEXT_PUBLIC_MICROSERVICE_SERVICE_URL + '/services',        {method: 'GET'});
        const data = await res.json();
        await setServices(data);
      } catch (error) {
        console.error('Error al realizar el fetch:', error);
      }
    };

After calling the function with await, I console.log(companies) and console.log(services) and is the previous data.

I tried adding these useEffects

useEffect(() => {
  console.log('Companies Updated', companies);
}, [companies]);

useEffect(() => {
  console.log('Services Updated', services);
}, [services]);

These work since it logs the updated value. When I call the function above and log everything it updates the values first but then goes back to the previous state, this image helps understand.

How can I fix this?

Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54
  • This will help: https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately – Ali Navidi Jun 23 '23 at 23:05

1 Answers1

0

This is because, setState is not executed immediately, if you want to access data that was recently updated you have two ways

  • Using useEffect
  • Or if you want immediately access data after setState (1 line below setState) use the same value that you are passing to setCompanies or set setServices

Extra tip: Don't use await setState because setState doesn't return a promise, it is not necessary to do

Yuu
  • 337
  • 1
  • 4
  • The useEffect by some reason wasn't working correctly for me but I changed my code for the second one and it worked! Thanks! – Alvaro Postigo Jun 24 '23 at 19:17