jeudi 9 juillet 2020

React : Updating and then accessing state after a network request in useEffect hook. State remains stale

Im trying to update and reference hasError state field inside of the initialization function of my component in order to control if a redirect happens after successful initialization or if error gets displayed.

Here is a condensed version of the issue:

const [hasError, setHasError] = useState(false);

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

async function initialize(){
  try {
    await networkRequest();
  } catch (err) {
    setHasError(true);
  }
  console.log(hasError);  // <- is still false
  if(!hasError){
    redirect()  // <- causes redirect even with error
  }
}

function networkRequest() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject();
    }, 1000);
  });
}

The initialization function should only be called once on component mount which is why I'm passing [] to useEffect. Passing [hasError] to useEffect also doesn't make sense since I don't want initialization to run everytime hasError updates.

I have seen people recommend using useReducer but that seems hacky since I'm already using Redux on this component and I'll need to use 2 different dispatch instances then.

How is a use case like this typically handled?




Aucun commentaire:

Enregistrer un commentaire