I am trying to move to RTK Query, but am struggling with one thing - how to access React Context.
I currently am using custom hooks to query a back end. Depending on the environment (dev, uat, prod), there will be different backend servers I need to call. I store these backend server addresses in context and can access it from my custom hooks. But if I move to RTK Query, I cannot get hold of the BackendServer Context.
How can I access context from the createApi() method of RTK Query? Or should I be storing these server addresses somewhere other than context?
src/BackendContext.ts
export const BackendServers {
Pokemon: string,
Marvel: string
}
const DEV: BackendServers = {
Pokemon: 'http://pokeapi-dev.co/',
Marvel: 'http://marvelapi-dev.com/'
}
const UAT: BackendServers = {
Pokemon: 'http://pokeapi-uat.co/',
Marvel: 'http://marvelapi-uat.com/'
}
export const BackendServersContext = createContext<BackendServers>(DEV);
src/main.tsx
<BackendSErversContext.Provider value={DEV}>
<App/>
</BackendServersContext>
src/hooks/useCustomHook.ts
export const useCustomHook = () => {
const backendServers = useContext(BackendServersContext);
console.log('This hook will be calling ' + backendServers.Pokemon);
....
}
How can I access context from the RTK Query createApi() function?
src/services/pokemon.ts
// Or from '@reduxjs/toolkit/query/react'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
export const pokemonApi = createApi({
baseQuery: fetchBaseQuery({
baseUrl: 'https://pokeapi.co/api/v2/' // !! How can I get this server name from context? !!
}),
endpoints: (build) => ({
getPokemonByName: build.query({
query: (name: string) => `pokemon/${name}`,
}),
}),
})