Home > Mobile >  Updating a dependency variable after execution of useEffect without triggering that useEffect hook a
Updating a dependency variable after execution of useEffect without triggering that useEffect hook a

Time:10-28

As shown in the following react code snippet, I have a useEffect hook with a dependency 'fetchQuery'. The useEffect hook will execute if 'fetchQuery' variable changes. But right after execution of it, I want to clear the value (set to '') of that dependency variable 'fetchQuery' without triggering an infinite loop. Is there a way to do that?

useEffect(() => {
        // An async function to fetch some data
        getDataModules(fetchQuery);
    }, [fetchQuery]);

Since 'fetchQuery' is a state variable and is given as a dependency for this hook, simply clearing its value using setFetchQuery(''); will trigger useEffect again, which I dont want.

CodePudding user response:

Only call the API if fetchQuery exists.

useEffect(() => {
    if (fetchQuery) {
        getDataModules(fetchQuery);
    }
}, [fetchQuery]);

Do setFetchQuery(''); to clear.

CodePudding user response:

const [shouldRefetch, setShouldRefetch] = useState(false);

const [fetchQuery, setFetchQuery] = useState(...);

useEffect(() => {
  if (shouldRefetch) {
    getDatamodules(fetchQuery);
    setShouldRefetch(false);
    setFetchQuery('');
  }
}, [shouldRefetch]);


const someOtherFunction = () => {
  setFetchQuery(...);
  SetShouldRefetch(true);
};
  • Related