13

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?

Community
  • 1
  • 1
simont
  • 441
  • 3
  • 7

3 Answers3

21

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: () => ({}),
});
Community
  • 1
  • 1
simont
  • 441
  • 3
  • 7
  • Hi, I am currently using this dynamic base query approach, but on my browser's Network tab, the request returns 404 with a incorrect `url`, apparently the `url` only stops at what the `dynamicBaseQuery` returns, but does not extend the endpoint's url, for example, expected should be `http://sample-url/verson1/data?anyparam=true`. `version1` is the dynamic var that comes from a request from the backend, but the actual `url` turns out to be `http://sample-url/version1/`, have you had similar issue before working with dynamic base query? – user14459580 Oct 26 '22 at 14:13
  • How can I tap into a store slice to get the baseUrl from there? – Walter Monecke Aug 04 '23 at 10:54
9

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.

phry
  • 35,762
  • 5
  • 67
  • 81
  • no, api in different from origin – simont Oct 14 '21 at 12:16
  • ? I meant where the example does `const adjustedUrl = \`project/${projectId}/${urlEnd}\`` you can also just do `const adjustedUrl = \`https://${somethingYouGotFromTheStore}/${urlEnd}\`` – phry Oct 14 '21 at 20:46
0

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',
  }),
}), }),});
Justin
  • 1
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Aug 28 '23 at 00:51