简体   繁体   中英

useSWR returning undefined data with axios in nextjs

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM