SWR Library loses data on refresh

26 views Asked by At

This is my page.jsx

'use client';

import Loader from "@/components/Elements/Loader";
//Layout Import
import useGetProjectsByUserId from "@/hooks/api/useGetProjectsByUserId";
export default function Profile({ params }) {

    const { data : user, error, isLoading } = useGetProjectsByUserId(params.id);
    return (
        <div>
          {isLoading && <Loader />}
          {error && <div><p className="p-4">Error fetching user data...</p></div>}
          {user && (
            <pre>
              {JSON.stringify(user,null,2)}
            </pre>
          )}
        </div>
    )
}

And this is my useGetProjectsByUserId.jsx hook

import useSWR from "swr"
import useApiService from "../useApiService";

async function fetcher(url, apiFunction) {
  try {
    const response = await apiFunction(url);
    return response;
  } catch (error) {
    console.error(`Error fetching data from ${url}`, error.message);
    throw error;
  }
}

export default function useGetProjectsByUserId(id) {
    const api = useApiService();
    
    const { data, error, isLoading } = useSWR(`/users/${id}`, (url) => fetcher(url, api.get));

    return {
        data,
        error,
        isLoading
    };
}

The data shows correctly on the initial page load but when I refresh the page it shows the loader for a second and displays a blank screen and the data shows up after a minute. On page refresh, i can see that an API call to 'users/${id}' in the network tab with the correct response but the data is not displayed instantly and only after a brief moment. What am i doing wrong ?

Thank you for your help !

0

There are 0 answers