Fetch an auth0 access token asynchronously from within react-query function

Viewed 27

I am using preact + react-query + auth0-react and have created a custom hook to retrieve data from an API.

So, here is a simplified version of the hook:

export const useGetData = () => {
    return useQuery(["test"],() => apiGet());
};

The generic API function obtains a token from Auth0 and then retrieves the data from the API:

export const apiGet = async () => {
    const { getAccessTokenSilently } = useAuth0();
    const token = await getAccessTokenSilently();
    const response = await axios.get("[API URL]", {
        headers: {
            Authorization: `Bearer ${token}`
        }
    });
    return response.data;
};

However, the call to useAuth0() fails with the following error:

Cannot read properties of null (reading 'context')

It seems the call to useContext from within useAuth0 is not finding the Preact context - is that because I am calling a hook from within a callback function?

I don't want to get the token within each hook as I would rather have all the token logic contained in the generic API function.

Any pointers greatly appreciated.

1 Answers

I ended up calling the useAuth0() hook from within my own hook and then passing that down to the API:

export const useGetData = () => {
    const auth = useAuth0();
    return useQuery(["test"],() => apiGet(auth));
};

export const apiGet = async (auth: Auth0ContextInterface<User>) => {
    const token = await auth.getAccessTokenSilently();
    const response = await axios.get("[API URL]", {
        headers: {
            Authorization: `Bearer ${token}`
        }
    });
    return response.data;
};

Not sure if there is a better way but this seems to work OK.

Related