How can I dynamically change the baseURL for specific resource whose RTK Query endpoints are injected via injectEndpoints
?
This is my use case:
I have 4 resources which I have split (4 files) with RTK's injectEndpoints()
functionality, which looks like this:
const resource1Api = emptyApi.injectEndpoints({
endpoints: (builder) => ({
getData: builder.query({
query: () => '/resource1/data'
})
}),
overrideExisting: false
});
const resource2Api = emptyApi.injectEndpoints({
endpoints: (builder) => ({
getData: builder.query({
query: () => '/resource2/data'
})
}),
overrideExisting: false
});
...etc
I would like to be able to override, individually, the baseURL for all of Resource1, or Resource2, etc. They all plug into a createApi()
call in a separate 5th file which looks like this:
const baseQuery = fetchBaseQuery({
baseUrl: `${process.env.REACT_APP_API_HOST}`
});
export const emptyApi = createApi({
baseQuery: baseQuery,
endpoints: () => ({})
});
In production, all resources use the same base url. For example, "baseURL/resource1/...", "baseURL/resource2/...", etc. However, in development, our team can individually override the endpoints for one or more of those resources by running a locally hosted version of the API for just that resource. So the endpoints across those resources look more like "baseURL/resource1/...", "localURL1/resource2/...", "baseURL/resource3/...", "localURL2/resource4/...".
If any of the API's are running locally, there is an individual environment variable for each of their URLs. Ideally, there would be a way to change the baseURL for the resource to the localURL only if that url is set.
The easiest way would be for you to just specify a full url for those endpoints:
query: () => myOtherBaseUrl + '/resource2/data'
You can also go more complicated, by adding DefinitionExtraOptions
to a wrapper-baseQuery and passing those into the hook, or by looking at baseQueryApi.endpoint
(available in RTK >=1.7) in a baseQuery
wrapper, but the above solution is probably the most simple.