简体   繁体   English

错误:无效的挂钩调用。 在等待之后调用钩子时 - 你如何等待来自一个钩子的数据实例化到另一个钩子?

[英]Error: Invalid hook call. when calling hook after await - how do you await for data from one hook to instantiate into another?

Im trying to inject a header into my fetcher before using swr to fetch the data.我试图在使用 swr 获取数据之前将 header 注入我的提取器。 I need to await for a custom hook to respond with the data before I can inject it into the custom fetcher.我需要等待自定义钩子响应数据,然后才能将其注入自定义提取器。

If I use a promise.then I know i'm getting the relevant data, and if I manually inject it using a string it works and i see the header.如果我使用 promise。那么我知道我正在获取相关数据,如果我使用字符串手动注入它,它可以工作并且我看到 header。 Its just doing it async它只是异步进行

How should I go about doing this?我应该如何 go 这样做?

Code:代码:

    export const useApi = async (gql: string) => {
      const { acquireToken } = useAuth()
      await acquireToken().then(res => { graphQLClient.setHeader('authorization', `Bearer ${res.accessToken}`) })
      const { data, error } = useSWR(gql, (query) => graphQLClient.request(query));
      const loading = !data
      
      return { data, error, loading }

   }

first, keep consistent your promises, use async/await or choose for chaining it with then , but not both.首先,保持您的承诺一致,使用 async/await 或选择将其与then链接,但不能同时使用两者。 if you await acquireToken() you can store its value in variable.如果您 await acquireToken()您可以将其值存储在变量中。 also, if you choose for async/await wrap your code with a try/catch block, for handling errors properly:此外,如果您选择 async/await 使用 try/catch 块包装您的代码,以便正确处理错误:

    export const useApi = async (gql: string) => {
      const { acquireToken } = useAuth()

      try {
        const res = await acquireToken()
        graphQLClient.setHeader('authorization', `Bearer ${res.accessToken}`)
        const { data, error } = useSWR(gql, (query) => graphQLClient.request(query))
        const loading = !data
      
        return { data, error, loading }

      catch(error) {
        // handle error
      }
   }

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

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