reactjsnext.jsreact-hooksswr

how to execute something once when data fetched by SWR is available (useEffect)


suppose I want to execute something once and only one time when SWR fetches the data and it's defined.

 const {
    data,
    isLoading,
    mutate,
 } = useSWR(`${process.env.BACKEND_BASE_URL}/resource`,fetcher);

usually, you would do this in a useEffect with no dependencies, but in this case, the data is undefined:

useEffect(() => {
    console.log(data) // data is undefined here !!!
}, []);

Of course, if I add data to the dependency list, it will be executed when data turns into a defined value but then it will also be executed every time data changes in the future, which is not what I want.

I would appreciate any help...


Solution

  • Use a Boolean ref to ensure that the useEffect is only executed once:

    const effectCalledRef = useRef(false);
    
    useEffect(() => {
      // check if data exists and the effect haven't been called
      if(data && !effectCalledRef .current) {
        console.log(data)
        effectCalledRef .current = true;
      }
    }, [data]);