5

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
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • 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()`. – Frederick M. Rogers Jul 26 '22 at 13:11
  • @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. – Gabriel Ferraz Nov 17 '22 at 22:01

1 Answers1

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.

Rob
  • 87
  • 7