How to access getTokenSilently() auth0 in RTK Query?
Asked Answered
D

1

6

I'm completely new to using RTK Query, I created the app before but without the authentication and everything worked, now I want to add the authentication using Auth0 but I can't access any file I add getTokenSilently() PS. getTokenSilently is the {token} thanks for help

export const myApi = createApi({
  reducerPath: "points",
  baseQuery: fetchBaseQuery({
    baseUrl: "/",
    prepareHeaders: (headers, { getState }) => {
      const token = getState()
      if (token) {
        headers.Authorization = `Bearer ${token}`
      }

      return headers
    },
  }),
  endpoints: builder => ({
    getPoints: builder.query({
      query: () => `/`,
    }),
  }),
})

export const { useGetPointsQuery } = myApi
Dasi answered 11/4, 2022 at 18:42 Comment(2)
I too am struggling with this. Mostly due to the fact that .getTokenSilently() return a promise. I am unsure how to resolve that promises in the context of RTK Query's createApi().Wardieu
@FrederickM.Rogers you can simply make prepareHeaders an async function and await getTokenSilently() in a try block to get the token. The problem here though is that getTokenSilently comes from a hook and hooks only work inside a React functional component (which the slice is not) so it is not possible to get the token directly that way. You would need to set the token to some global state that you can access on the slice or use the auth0-spa library.Magyar
L
0

What I ended up doing was to store the token in my state and then added this to App:

  useEffect(() => {
    (async () => {
      try {
        const token = await getAccessTokenSilently({})
        dispatch(setToken(token))
      } catch (e) {
        console.error(e);
      }
    })()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [getAccessTokenSilently])

There is a little more logic to know if you have not yet authenticated so that you can render a pending authentication state, but this was enough to get me going.

Lobachevsky answered 27/7, 2022 at 2:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.