Home > Enterprise >  Use effect wait for Data from previous page
Use effect wait for Data from previous page

Time:04-11

I'm kinda new to the react framework. As per my requirement , I want to wait until data arrives and binds to my constants in my useEffect() method.

The data is sent encrypted from the main page and is decrypted as follows :

useEffect(() => {
    const DecryptedGroupID = atob(groupID.toString());
    const DecryptedFactoryID = atob(factoryID.toString());

    setProfitAndLossDetails({
      ...ProfitAndLossDetails,
      groupID: DecryptedGroupID,
      factoryID: DecryptedFactoryID
    });
  }, []);

I want to add a waiter/timer/delay to wait until the data gets bound to my const variables. (atob is a decrypting function).

The groupID is required to generate the factoryIDs for the specific group, hence during page reload since it takes time / delay for the hooks to bind, the factoryIDs won't load at times(however when refreshing it appears sometimes), I think adding a delay and giving it time to bind might fix this issue.

CodePudding user response:

Just add groupID and factoryID as your useEffect dependencies. Hook will be called automatically when they are changed. Inside hook you can check if groupID and factoryID not empty, and call your setter function.

Read more about how this hook work: https://reactjs.org/docs/hooks-reference.html#useeffect

CodePudding user response:

You need to:

  • Test in the hook if they are defined or not
  • Call the effect hook when the values you are depending on change (so the hook doesn't run once when they aren't defined and then never run again) — add them to the dependency array.

Such:

useEffect(() => {
    if (!groupID || !factoryID) return;

    // Otherwise don't return and use them with their values
}, [groupID, factoryID]);
  • Related