Home > Net >  useSWR returning undefined data with axios in nextjs
useSWR returning undefined data with axios in nextjs

Time:07-07

I have a useSubjects custom hook to fetch the data from my API endpoint that utilizes useSWR.

import axios from '@/lib/axios'
import useSWR from 'swr'

/**
 * Fetcher Function for SWR
 */
const fetchSubjects = async url => {
    console.log("url = "   url)
    await axios
        .get(url)
        .then(res => res.data)
        .catch(error => {
            if (error.response.status !== 409) throw error
        })
}

export const useSubjects = (id = -1) => {
    // /**
    //  * swr hook for fetching subjects
    //  */
    const { data: subjects, error, mutate } = useSWR(
        id > 0 ? `api/get-subject-branch/${id}` : 'api/get-subject-branches',
        fetchSubjects,
    )

    return {
        subjects,
        error,
    }
}

The useSubjects hook is later used in one of my components.

import { useEffect } from 'react'
import { useSubjects } from '@/hooks/subjects'

const myComponent = () => {
   const { subjects, error } = useSubjects()

    useEffect(() => {
        console.log(subjects)
    }, [subjects])

   return (
      <>
         <div>My Content</div>
      </>
   )
}

However, the constant {subjects} which should hold the fetched data from the useSWR hook seems to remain undefined

I have tested out my API endpoint using direct axios GET request and it successfully pulls the data from my API.

In fact, I have written console.log(res.data) in my fetchSubjects fetcher function that seems to get the data. But it is somehow it is not setting the const {data: subjects, ...} that should hold the data fetched from the API and it remains undefined

CodePudding user response:

You are not returning anything from the fetcher , it should be

const fetchSubjects = async (url: string) => {
    console.log("url = "   url)
     return await axios
        .get(url)
        .then(res => res.data)
        .catch(error => {
            if (error.response.status !== 409) throw error
        })
}

check this working example https://codesandbox.io/s/swr-axios-forked-r4loo6

  • Related