next.js SWR在第二次请求后返回错误数据

ruarlubt  于 2023-01-30  发布在  其他
关注(0)|答案(2)|浏览(225)

在我第二次向/api/individual端点请求获取数据后,当我在不刷新浏览器的情况下查询该端点时,useSWR返回了错误的负载。但是,当我重新加载网页时,它返回了正确的数据。以下是我第一次收到的数据。端点:http://localhost:3000/api/individual?section=Congress%20Services&individual_id=1

{
    "data": [
        {
            "_id": {
                "$oid": "61ece7a3570c0b5a211c86b0"
            },
            "individual_id": 1,
            "sections": {
                "Event Services": {
                    "Choose language for translation": "Russian",
                    "Do you need a letter of invitation": "No",
                    "Family Program (Extra fee)": "No",
                    "Translation needed": "Yes"
                }
            }
        }
    ]
}

加载相同端点但请求不同数据http://localhost:3000/api/individual?section=Agreement%20to%20publish&individual_id=1

{
    "data": [
        {
            "_id": {
                "$oid": "61ece7a3570c0b5a211c86b0"
            },
            "individual_id": 1,
            "sections": {
                "Agreement to publish": {
                    "Agreement to publish": "No"
                }
            }
        }
    ]
}

然后,我加载上一个端点..但收到的数据与第一次不同。端点:http://localhost:3000/api/individual?section=Congress%20Services&individual_id=1

[
    {
        "_id": {
            "$oid": "61ece7a3570c0b5a211c86b0"
        },
        "individual_id": 1,
        "sections": {
            "Event Services": {
                "Do you need a letter of invitation to obtain a visa": "No",
                "Family Program (Extra fee)": "No",
                "Translation needed": "Yes"
            }
        }
    }
]

然而,如果我看网络选项卡,我注意到网络选项卡返回了正确的数据,但useSWR没有。我还注意到,如果我添加一个随机比较选项useSWR,如...

options: {
  compare: (a, b) => {
    console.log("A", a)
    console.log("B", b)

  }
}

窃听器消失了......知道是什么原因吗?
我的fetcher和useSWR函数看起来像...

async function fetcher(...args) {
  const url = args[0]
  const token = args[1]
  const method = args.length > 2 ? args[2] : 'GET'
  const body = args.length > 3 ? { body: JSON.stringify(args[3]) } : {}
  const res = await fetch(url, {
    method: method,

    headers:
      method != 'GET'
        ? {
            Authorization: `bearer ${token}`,
            'Content-Type': 'application/json',
          }
        : {
            Authorization: `Bearer ${token}`,
          },
    ...body,
  })

  if (!res.ok) {
    const error = new Error('An error occurred while fetching the data.')
    // Attach extra info to the error object.
    error.info = await res.json()
    error.status = res.status
    throw error
  }

  return res.json()
}

function useSWRFetch({ endpoint, token, options = null, condition=true }) {
  const { data, error, mutate } = useSWR(token && condition ? [endpoint, token] : null, fetcher, options)

  return {
    mutate: mutate,
    data: data,
    isLoading: !error && !data,
    error: error,
  }
}

我是这么称呼它的...

const formQuestionsResponse = useSWRFetch({
    endpoint: `/api/individual?section=${section}&individual_id=${id}`,
    token: authToken,
    condition: isCurrentSelectedTab,
    // options: {
    //   compare: (a, b) => {
    //     console.log("A", a, 'B', b)
    //   }
    // }
  })

我还注意到,如果我在fetcher函数中使用console.log记录数据,它会返回我在网络选项卡中看到的正确数据,但如果我在它经过useSWR之后使用console.log记录数据,则数据缺少一个属性。

wvmv3b1j

wvmv3b1j1#

为了解决这个问题,我在useEffect中执行了一个清理操作。当我在两个部分之间单击时,我将数据设置回了null。我相信有某种内存泄漏发生了。

sh7euo9m

sh7euo9m2#

当你遇到错误时,这个数据不会被重置,因为你可能想显示乐观数据。你可以通过调用mutate(null)来清除数据,但是要小心它会重置数据(在swr缓存中也是这样吗?)。
在 * useSWRMutation * 的情况下,您可以使用 * reset * 功能清除所有(数据、错误、isMutating)
参考:www.example.comhttps://swr.vercel.app/docs/mutation#return-values-1

相关问题