-1

I am trying to use SWR in Next.js for the first time. I am using Axios to make http calls. The Axios make calls to protected API routes and I handled that using interceptor. Here is one of the places where I used the SWR but I am getting undefined when I console.log(data) from SWR;

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

        return res.data;
    } catch (error) {
        return error
    }
    
}


const { data, error, isLoading } = useSWR(`${getcompany`, getProfile)

What Am I doing wrongly?

1 Answers1

0

There is a syntax error:

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

const { data, error, isValidating } = useSWR('/getcompany', getProfile);

useSWR's first argument should be a string that serves as a key to identify the data (typically it's the API endpoint). The second argument is the fetcher function, which is getProfile in this case.

jagmitg
  • 4,236
  • 7
  • 25
  • 59
  • It is still showing undefined. Where is the syntax error? – princekings Jul 13 '23 at 12:08
  • Literally type you had it as the following ```${getcompany``` but it should be ```${getcompany}``` – jagmitg Jul 13 '23 at 12:09
  • The axios response worked when I checked it inside the getProfile function. I can see the data that I fetched. However, SWR is not working, showing undefined and error is false. – princekings Jul 13 '23 at 12:13
  • hmm - try this ```if (isValidating) { return
    Loading...
    ; } if (error) { return
    Error: {error.message}
    ; }``` Make sure your *getProfile* function returns a JSON object. If not, this could be the issue. If the problem continues, share more code or details for better help.
    – jagmitg Jul 13 '23 at 12:16