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),
})