0

I developed a site using React and Auth0, separately about queries there is no problem, but because I have many queries I have to do all queries in one file: I used redux toolkit query but I have trouble getting authentication token as shown in the example.

I also used react query I had the same issue about authentication token , overcame it with custom hooks but got many re-renders , almost the same issue with use-context. In short, my app is working fine, but I'm looking for a solution in terms of organisational and also data consumption.

import React from "react"
import { Auth0Provider } from "../services/auth"

const App = ({ element, location }) => {
  const onRedirectCallback = appState => {
    location.navigate(
      appState && appState.targetUrl
        ? appState.targetUrl
        : window.location.pathname
    )
  }

  return (
    <Auth0Provider
      domain={process.env.GATSBY_AUTH0_DOMAIN}
      client_id={process.env.GATSBY_AUTH0_CLIENT_ID}
      redirect_uri={process.env.GATSBY_AUTH0_CALLBACK}
      cacheLocation="localstorage"
      onRedirectCallback={onRedirectCallback}
      audience={process.env.GATSBY_AUTH0_AUDIENCE}
      scope={process.env.GATSBY_AUTH0_SCOPE}
    >
      {element}
    </Auth0Provider>
  )
}

export default App

/* ========================================== */

/* With redux toolkit query */
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"

export const pointsApi = createApi({
  reducerPath: "points",
  baseQuery: fetchBaseQuery({
    baseUrl: "/",
    prepareHeaders: (headers, { getState }) => {
      const token = getState() // <--- I need to get the token , const { getTokenSilently } = useAuth0()
      if (token) {
        headers.Authorization = `Bearer ${token}`
      }

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

export const { useGetPointsQuery } = pointsApi

/* =================================== */

import { configureStore } from "@reduxjs/toolkit"
import { pointsApi } from "../services/usersPointsApi"

export default configureStore({
  reducer: {
    [pointsApi.reducerPath]: pointsApi.reducer,
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware().concat(pointsApi.middleware),
})
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • This question is not really a question. Could you try making it more focused on one or more of your pain points? A general question in terms of "how do I structure my entire app" is not answerable really. – Jakub Kotrs Apr 13 '22 at 20:59
  • Thanks for your comment, all what I need just add const { getTokenSilently } = useAuth0() to getState() for the token @JakubKotrs – Yasser Mahmoud Apr 13 '22 at 21:09

0 Answers0