How to access getTokenSilently() auth0 in RTK Query?

Viewed 317

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

1 Answers

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.

Related