How to dynamically change base URL using redux-toolkit?
Asked Answered
F

3

16

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?

Fault answered 14/10, 2021 at 10:8 Comment(0)
F
22

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: () => ({}),
});
Fault answered 14/10, 2021 at 12:21 Comment(2)
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?Replay
How can I tap into a store slice to get the baseUrl from there?Maurinemaurise
C
13

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.

Cripps answered 14/10, 2021 at 10:32 Comment(2)
no, api in different from originFault
? I meant where the example does const adjustedUrl = `project/${projectId}/${urlEnd}` you can also just do const adjustedUrl = `https://${somethingYouGotFromTheStore}/${urlEnd}`Cripps
K
1

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',
  }),
}), }),});
Kneepan answered 21/8, 2023 at 20:4 Comment(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?Sorcim

© 2022 - 2024 — McMap. All rights reserved.