React hooks state is not updated right after it's set with async

心不动则不痛 提交于 2021-01-29 19:56:44

问题


Is it not possible to get the updated hook value right after setting it? I assume react only updates value for the next render, since my screen following async-await renders fine. Just logs are not printing out the state I was expecting.

Not sure if I'm suppose to log state like this, or write another useEffect just for the states I need and put console.log in there instead?

const [uid, setUID] = useState<string | undefined>(undefined);
const [state, setState] = useState<{ [key: string]: any; } | undefined>();

const load = async () => {
  const currentUID = auth().currentUser?.uid;
  setUID(currentUID);

  console.log(uid); // returns undefined
  console.log(currentUID); // this prints fine

  await firestore().collection('users').doc(currentUID).get().then(docSnapshot => {
    setState(docSnapshot.data());
    console.log('Profile: loaded', state); // returns undefined
  });

  console.log(uid); // returns undefined even after await
  console.log('Profile: loaded', state); // returns undefined even after await
}

useEffect(() => { 
  load();
}, []);

回答1:


State updates are internally async, meaning state setter calls ( setState() from useState or this.setState() for class components) do not return a promise. This means that calling await on it isn't going to do anything, and synchronous logic after the await call is going to still run before state has been updated.

So there is a fix

// Either log it directly in the body of the function
console.log(state);

// ...Or in a useEffect call
useEffect(() => {
  console.log(state);
}, [state]);

const handleEvent = e => {
  setState(e.target.value);
}

Or class components provide a callback.

this.setState({value: newValue}, () => console.log(this.state.value))

Read more here



来源:https://stackoverflow.com/questions/61947321/react-hooks-state-is-not-updated-right-after-its-set-with-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!