Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define common query params in Redux Toolkit Query

All the endpoints of the API I’m working on, require the same set of query parameters. The user must select these parameters before making requests to endpoints.

Examples of endpoints

/api/resource-1?param1=valueA&param2=valueB&param3=valueC
/api/resource-2?param1=valueA&param2=valueB&param3=valueC

Selected values are saved on the Redux Store. I’d like to customize my baseQuery to append these query params to API URL automatically. I’m searching something in fetchBaseQuery that works similar to prepareHeaders allowing to customize the query URL.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hypothetical code

const baseQuery = fetchBaseQuery({
  baseUrl: baseUrl,
  // THIS PROPERTY DOES NOT EXISTS
  prepareUrl: (url, { getState }) => {
    const param1 = (getState() as AppState).config.param;
    if (param1) {
      url.searchParams.append('param1', param1);
    }
    return url;
  },
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as AppState).auth.token;
    if (token) {
      headers.set('authorization', `Bearer ${token}`);
    }
    return headers;
  },
});

I read how to implement a custom base query but I don’t want to lose the behavior provided by fetchBaseQuery.

Is there something like the prepareUrl property that allows to customize the request URL? Should I implement a custom base query? What’s the best way to do that?

>Solution :

You were already on the right page in the docs. The trick is to not write a completely new baseQuery, but to wrap a custom baseQuery "around" the existing implementation. This examples shows how to do that to get a dynamic baseUrl, which should be very close to what you want to do here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading