React hook useSelector value not changed inside async function

8.4k views Asked by At

I've been using React Hook with useSelector and useDispatch for a while, mostly it works very well but recently I've experienced some very wired scenario. For example

// parentComponent
const MyComponent = (props) => {
  const hasChanged = useSelector(state => {
    const isChanged = checkIfChanged(state);
    console.log('useSelector isChanged:>> ', isChanged);
    return isChanged;
  });

  const selectChange = async(userId, userCode)=> {
    console.log('selectChange hasChanged :>> ', hasChanged);
    // ...
  }
  return (
      <div>
        <ChildComponent onSelectChange={selectChange} />
      </div>
  );
}

I have my properties saved in the state and whenever there is anything changed in my component, my hasChanged from useSelector will become true, however, when I made a change, I can see my hasChanged already become true in the useSelector, but still false inside my function selectChange!

console log
useSelector isChanged:>> true
useSelector isChanged:>> true
selectChange hasChanged :>> false // why it's false here as already true from useSelector
useSelector isChanged:>> true

Does anyone have the same experience? I am wondering if it's because my selectChanged is async-await so the value inside will not fetch from the latest state?

1

There are 1 answers

3
Ryuko On

I think you should use useEffect();

const {userId, userCode} = useSelector(state => { /* ... */ });
const selectChange = async () => {
    if (hasChanged) {
      await dispatch(notifyUser(userId, userCode));
    } else {
      await dispatch(redirectPage(userCode));
    }
}

useEffect(() => {
    selectChange();
}, [hasChanged]); 
return (
   <div>
       <Select />
   </div>
);