0

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...

1 Answer 1

0

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]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.