I use the redux toolkit to create an API The question is short: how to dynamically change the baseUrl in the API? The question in detail: Here is the createApi method An object is passed to this method, one of the keys of which is "baseQuery"
export const WebApi = createApi({
reducerPath: 'API',
baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:3001/api' }),
endpoints: () => ({}),
});
And here's the question, how do I dynamically change the baseUrl? It is in the store, but I can't just put it here. I tried the solution from the customization query documentation https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#constructing-a-dynamic-base-url-using-redux-state
But it does not allow to change exactly the baseUrl, only dynamically process the request itself, which already comes AFTER the baseUrl
So, how can I get and change baseUrl in the createApi method?
So, the answer is:
right in the file where you create api past code below:
const dynamicBaseQuery: BaseQueryFn<string | FetchArgs,
unknown,
FetchBaseQueryError> = async (args, WebApi, extraOptions) => {
const baseUrl = (WebApi.getState() as any).configuration.baseUrl;
const rawBaseQuery = fetchBaseQuery({ baseUrl });
return rawBaseQuery(args, WebApi, extraOptions);
};
I use baseUrl from store, because my config already in it. But you can make an async await fetch here, to get data from any place
and this constant, dynamicBaseQuery insert into baseQuery key in your createApi
export const WebApi = createApi({
reducerPath: 'API',
baseQuery: dynamicBaseQuery,
endpoints: () => ({}),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With