0

I'm using Tanstack query to fetch data from the back end. The purpose is to have a generic function which would authorize the user before fetching the data.

const queryClient = new QueryClient()

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement)
root.render(
  <React.StrictMode>
    <ChakraProvider theme={theme}>
      <QueryClientProvider client={queryClient}>
        <Router basename={process.env.PUBLIC_URL}>
          <Auth0ProviderWithHistory>
            <App />
          </Auth0ProviderWithHistory>
        </Router>
      </QueryClientProvider>
    </ChakraProvider>
  </React.StrictMode>
)

Then I have this useFetch function

//useFetch.js

import axios, { Method } from "axios"
import { audience } from "../utils/dataUrls"
import { useAuth0 } from "@auth0/auth0-react"

const base = {
  "Access-Control-Allow-Origin": process.env.REACT_APP_ACCESS_CORS || ""
}
const { getAccessTokenSilently, getAccessTokenWithPopup } = useAuth0()

const useFetch = async (url: string, method: Method, headers?: Record<string, any>, body?: unknown) => {
  const tokenGetter =
    process.env.REACT_APP_ENVIRONMENT === "local" ? getAccessTokenWithPopup : getAccessTokenSilently

  const token = await tokenGetter({
    audience: audience
  })
  const { data } = await axios.request({
    url,
    headers: { ...base, Authorization: `Bearer ${token}` },
    method,
    data: body
  })
  return data
}

export default useFetch

And finally, when I try to call the function using useQuery (Inside a functional component) like this -

  const checkIfTokenExists = async () => {
    const test = useQuery(["getExistingPAT"], await useFetch(`${personalAccessToken}`, "get"))
    console.log(test)
  }
  // const { status, data, isFetching } = checkIfTokenExists()
  // console.log(status, data, isFetching)
  useEffect(() => {
    checkIfTokenExists()
  }, [])

I am getting the following error: Warning: Invalid hook call. Hooks can only be called inside of the body of a function component.

Any suggestions on how I could fix this please?

1
  • 1
    Yeah you're gonna have to put your hooks in the body. You can't use hooks in a function. so x = useFetch(), y = useQuery([], x) Commented Aug 17, 2022 at 18:17

1 Answer 1

0

Please have a look at this Github issue where jrozbicki describes a good solution for this problem. It is not necessary to create a custom hook to handle the authorization logic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.