-1

It is my first time of using SWR. Maybe I am wrongly implementing it. After implementing the SWR wrapper, I continued to get endless and repeated API call to the same endpoint. I saw this when I checked the Network tab of my browser: Here is how I implemented it.

 const getProfile = async () => {
    try {
        const res = await axiosPrivate.get<axiosGetCompanyProfile>(`/getcompany`, {
            withCredentials: true,
            headers: { Authorization: `${state?.in_memory}` },
        });
        console.log(res?.data, 'pro')
        return res.data;
    } catch (error) {
        throw error;
    }
};

const { data:fetchProfile, error, isLoading } = useSWR('/api/data', getProfile);


//fetch profile
 useEffect(()=>{

if(fetchProfile){
 dispatch({type: actionEnum.COMPANY_PROFILE_DATA, payload: fetchProfile });
return 
}
}, [isLoading]);

I noticed that the API calls happens whenever I leave the browser and returns. But from the look of things, it doesnt hit my server. So, why is it recalling it? Here is a screnshot:

request screenshot

1 Answers1

0

It's the default behaviour for data revalidation, in this case it's "revalidation on focus" (link). You can disable it via the revalidateOnFocus option. If you want to fetch data just once you can use useSWRImmutable hook (import useSWRImmutable from 'swr/immutable')

Check this docs page for more info

Danila
  • 15,606
  • 2
  • 35
  • 67
  • Yea, I found out that was the case. But I want to know, when this revalidation happen, do they hit the server or they are called from the cache? – princekings Jul 13 '23 at 21:13
  • They hit the server, of course, because otherwise it would not get the new data, right? Only the server has potential new data. – Danila Jul 14 '23 at 07:42
  • wow, how can something hitting the server that often be cool? Maybe in some situations where it is needed. Maybe – princekings Jul 15 '23 at 06:26