Search code examples
reactjsswr

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. 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. Its just doing it async

How should I go about doing this?

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 }

   }

Solution

  • first, keep consistent your promises, use async/await or choose for chaining it with then, but not both. if you await acquireToken() you can store its value in variable. also, if you choose for async/await wrap your code with a try/catch block, for handling errors properly:

        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
          }
       }