如何在NextJs中单击按钮时使用swr启动呼叫?

yvfmudvl  于 2023-06-05  发布在  其他
关注(0)|答案(2)|浏览(150)

我试图使用useSWR在点击按钮。我希望在单击按钮时,使用useSWR的API调用将启动,但我得到错误。错误是这样的:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

这是我的代码:

const onStartPro =() => {
    const token = session?.user?.access_token
    const url = process.env.BASE_URL + GET_PRO

    const {
      data: items,
      error,
      isLoading,
    } = useSWR(process.env.BASE_URL + 'pro user', getAuthenticatedClientSide(token,GET_PRO))
    
  }

这是我的get函数:

export const getAuthenticatedClientSide = async (token, endpoint) => {
  const url = process.env.BASE_URL + endpoint
  try {
    const res = await wretch(url).auth(`Bearer ${token}`).get().json()
    return res
  } catch (e) {
    const error = new Error(e)
    error.info = e.message
    error.status = e.status
    throw error
  }
}

我哪里错了?请帮帮我:(

oaxa6hgo

oaxa6hgo1#

useSwr是一个钩子函数,它和useEffect一样。所以你不能在事件函数内部使用。你应该尝试axios或fetch,就像你的event fun中的普通函数ccall一样。
使用提取器函数

export const fetcher = async (path: string) => {
  const res = await fetch(`${API_URL}${path}`, {
    headers: {
      Authorization: TOKEN || '',
      Accept: 'application/json, text/plain, */*',
      'User-Agent': '*'
    }
  });
const res = await fetcher(`/users`);
zzlelutf

zzlelutf2#

如果你想在这个方法中调用一个SWR,你必须在useEffect中使用它如果你只想调用一次,你必须像这样传递一个变量给useEffect

let onceCall = 1

useEffect(() => {
  const onStartPro = () => {
    const token = session?.user?.access_token
    const url = process.env.BASE_URL + GET_PRO

    const {
      data: items,
      error,
      isLoading,
    } = useSWR(process.env.BASE_URL + 'pro user', getAuthenticatedClientSide(token, GET_PRO))

  }

  if (onceCall <= 1) {
    onStartPro()
    onceCall += 1
  }

}, [onceCall])

相关问题