简体   繁体   English

useSWR 在 nextjs 中使用 axios 返回未定义的数据

[英]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.我有一个 useSubjects 自定义钩子来从我使用 useSWR 的 API 端点获取数据。

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. useSubjects 挂钩稍后在我的一个组件中使用。

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但是,应该保存从 useSWR 挂钩获取的数据的constant {subjects}似乎仍未undefined

I have tested out my API endpoint using direct axios GET request and it successfully pulls the data from my API.我已经使用直接axios GET请求测试了我的 API 端点,它成功地从我的 API 中提取数据。

In fact, I have written console.log(res.data) in my fetchSubjects fetcher function that seems to get the data.事实上,我已经在我的fetchSubjects函数中编写了console.log(res.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但不知何故,它没有设置应该保存从 API 获取的数据的const {data: subjects, ...}并且它仍然undefined

You are not returning anything from the fetcher , it should be你没有从 fetcher 返回任何东西,它应该是

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检查这个工作示例https://codesandbox.io/s/swr-axios-forked-r4loo6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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