Is there any better solution to this when the first useEffect fires, only getAccountDetailsData() will be successful, getErrorLogInfo() will fail because store.AccountDetails.ID is null at that stage. getAccountDetailsData() will get that value.
Now the use effect does not fire again, but waits 60 seconds to fire the 2nd one which fires every minute. and then everything works fine.
The problem is that I have to wait 1 minutes before I get getErrorLogInfo() to work. if I put a dependency list [] in the first useEffect() it will fire in loops. I won't have to wait for 1 minute but it will trigger a 429 error
useEffect(() => {
dispatch(getAccountDetailsData(user.EmailAddress)); // we call this to get AccountDetails.ID
dispatch(getErrorLogInfo(store.AccountDetails.ID)); // will not work missing AccountDetails.ID
}, []); // I can put dependency list [] but will be endless loop
//now I have to wait 60 seconds to try again
useEffect(() => {
dispatch(getAccountDetailsData(user.EmailAddress)); works
dispatch(getErrorLogInfo(store.AccountDetails.ID)); works
}, 60000);// refresh data after every 60 seconds
return () => clearInterval(interval);
}, [store]);
CodePudding user response:
if you want to fetch data depending on store data u can do it with 2 useEffect
like this:
useEffect(() => {
dispatch(getAccountDetailsData(user.EmailAddress));
}, [])
useEffect(()=>{
if(store.AccountDetails){
dispatch(getErrorLogInfo(store.AccountDetails.ID));
}
},[store.AccountDetails])
CodePudding user response:
You'll need to put a guard statement on your useEffect
callback to prevent it from attempting to getErrorLogInfo
before store.AccountDetails.ID
is set.
Also split up to using two useEffect
statements since they will have different dependencies:
useEffect(() => {
if (user?.EmailAddress) // checks if it exists before running the dispatch
dispatch(getAccountDetailsData(user.EmailAddress));
}, [user?.EmailAddress]) // gets called once upon mount and if `user.EmailAddress` changes
useEffect(() => {
if (store?.AccountDetails?.ID) // checks if it exists before running the dispatch
dispatch(getErrorLogInfo(store.AccountDetails.ID))
}, [store?.AccountDetails?.ID]) // gets called once upon mount and if `user.EmailAddress` changes