I'm using redux-saga to fetch data from API and for that my code looks something like this.
useEffect(()=>{
getListFromAPI(); // dispatches an action that fetches data
getDataByResponseFromList(list.userName); // I also need to call another API depending on response from first API.
}, []);
getDataByResponseFromList(list.userName) fetches data from API depending on response from the getListFromAPI().
This resulted in an error "list.userName not defined", which was obvious because list is not defined yet.
to fix this I wrote another useEffect like below.
useEffect(()=>{
if(!Empty(list))
getDataByResponseFromList(list.userName);
}, [list]);
This worked fine, but in other situation I also need to call this code when one more state changes which is a general "connection" state. So my code becomes something like this.
useEffect(()=>{
if(!Empty(list) && connection)
getDataByResponseFromList(list.userName);
}, [list, connection]);
But now on page load this code runs two times, once when list is populated and once connection is setup, I know exactly the problem is occurring but I'm not sure about the right way to fix this. what is right way to fix such issues.
A Solution I tried :
As a solution I created a global variable to keep track for only one time execution.
let firstTimeExecution = true; // for only onetime execution
export const MyComponent = ({propsList}) => {
...
useEffect(()=>{
if(!Empty(list) && connection && firstTimeExecution){
getDataByResponseFromList(list.userName);
firstTimeExecution = false;
}
}, [list, connection]);
}
This worked perfectly but I'm not sure if this is the best practice and if I should do that.