3

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.

paullc
  • 155
  • 2
  • 9

1 Answers1

2

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.

phry
  • 35,762
  • 5
  • 67
  • 81
  • Thank you, is there some documentation around ExtraOptions? I haven't seen much of it at all in the docs. Thanks for any help! – paullc Nov 22 '21 at 23:06
  • It is not deeply covered. `retry` uses it and so it's final usage is shown in https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#automatic-retries As for implementing it, you can take a look at the source of retry: https://github.com/reduxjs/redux-toolkit/blob/2964b911156651fbedc8a2f69eab720154b07caf/packages/toolkit/src/query/retry.ts#L47 – phry Nov 23 '21 at 07:27