simont
simont

Reputation: 491

How to dynamically change base URL using redux-toolkit?

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?

Upvotes: 16

Views: 15048

Answers (3)

Justin
Justin

Reputation: 11

I'm probably late to the party but I just wanted to share an extended alternative.

const rawBaseQuery = (baseUrl: string) => fetchBaseQuery({baseUrl: baseUrl});

export function baseQuery(baseUrl: string) : BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> {
return async (args, api, extraOptions) => {

    let result = await rawBaseQuery(baseUrl)(args, api, extraOptions);
    // more logic can go here
}};

// and to use it

const api = createApi({  reducerPath: 'my-api', baseQuery: baseQuery(BASE_URL),   endpoints: (builder) => ({
helloWorld: builder.query<string, string>({
  query: (arg) => ({
    url: '/helloworld',
    credentials: 'include',
  }),
}), }),});

Upvotes: 1

simont
simont

Reputation: 491

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: () => ({}),
});

Upvotes: 23

phry
phry

Reputation: 44216

If you pass in a full url (starting with http:// or https://) fetchBaseQuery will skip baseUrl and use the supplied url instead. So you can use the logic that you linked above to just prepend your current baseUrl to the url of the query.

Upvotes: 14

Related Questions