我不应该在Next.js中使用axios吗?

xwbd5t1u  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(140)

与此同时,我一直在使用axios轻松地获取数据。当我转到Next.js时,我意识到axios不允许缓存,所以当多个组件获取同一个URL时,它们会请求大量数据。我认为我应该使用fetch,但是fetch很不方便。我不喜欢改为json的想法,并且必须指定返回类型和头部。当你使用fetch而不是axios时,在实践中使用Next.js?我很想知道实践开发人员如何获取数据。请让我知道你的想法
如果我使用fetch,我想我不需要使用react-query,因为缓存...你在实践中使用什么?

hjzp0vay

hjzp0vay1#

我使用RTK查询获取数据和fetch的一些地方。但我创建了一个自定义fetcher函数,并使用如下

export default async function fetcher(
  endpoint,
  {token, body, ...customConfig} = {}
) {
  const headers = {'Content-Type': 'application/json'}

  if (token) {
    headers.Authorization = `Bearer ${token}`
  }

  const config = {
    method: body ? 'POST' : 'GET',
    ...customConfig,
    headers: {
      ...headers,
      ...customConfig.headers,
    },
  }

  if (body) {
    config.body = JSON.stringify(body)
  }

  let response
  try {
    response = await fetch(endpoint, config)
    if (response?.ok) {
      return await response.json()
    }

    throw new Error('Server returned ' + response.status)
  } catch (error) {
    console.error('There was a problem with the Fetch operation,', error)
    return null
  }
}

字符串
然后像这样使用fetcher函数

try {
  const {data: response} = await fetcher(endpoint)

  if (response.status === 200) {
    return response
  }
} catch (error) {
  console.log('========================================')
  console.error('error in function name', error)
  console.log('========================================')
  return {}
}


如果你打算使用fetch,你应该使用你的自定义fetcher函数,而不是使用fetch的典型用法。希望你能得到一个想法。

相关问题