2

I am using hooks in react native. And something happens, when I update a state the value is not assigned immediately. This is my example code.

async function updateDeviceAdminAttributes(Token) {
    await getAdminAttributes(Token); //This function update objWithRPC
    if(objWithRPC != null) 
    {
      setDeviceAdminAttributes(objWithRPC);
      console.log(deviceAdminAttributes); //this return object {} 
    } else {
      setDeviceAdminAttributes({});
      console.log(deviceAdminAttributes); //this return  Object{ rpc1 : true }
    }
  }

I am working with react native and the getAdminAttributes function is a GET request from an API that updates the objWithRPC object. This function is activated when I change the value of a Picker (in app react native), change the value of the picker and it makes me the query that updates the value of objWithRPC. if the query does not contain data then it throws me a null if not then the object

This variable is updated correctly and when entering the conditional if (objWithRPC! = Null) Enter the places that should go the problem is that there I update a variable through the useState hook.

Doing so returns obj = {} and if I change the request so that it returns null there it should return obj = {} but now if it returns the previous object as it should be

Why is this happening?

ardoYep
  • 107
  • 3
  • 15

1 Answers1

1

This is because the change of state is asynchronous

If you want to track the change of state you can do so using useEffect

useEffect(() => {
    console.log(deviceAdminAttributes);
}, [deviceAdminAttributes]);
Yoel
  • 7,555
  • 6
  • 27
  • 59