Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

411
Visualizações
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.

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is my custom query code I ended up with:

import { fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { FetchArgs } from '@reduxjs/toolkit/dist/query/fetchBaseQuery'
import { BaseQueryApi } from '@reduxjs/toolkit/dist/query/baseQueryTypes';
import { RootState } from '../store';

const customQuery = async (args: string | FetchArgs, api: BaseQueryApi, extraOptions: {}) => {
    args = appendQueryStringParam(args, "Source", "Desktop");
    args = appendQueryStringParam(args, "LoginToken", "XYZ");

    return await fetchBaseQuery({ baseUrl: 'http://example.com/api' })(args, api, extraOptions);
}

function appendQueryStringParam(args: string | FetchArgs, key: string, value: string): string | FetchArgs {
    let urlEnd = typeof args === 'string' ? args : args.url;

    if (urlEnd.indexOf('?') < 0)
        urlEnd += '?';
    else
        urlEnd += '&';

    urlEnd += `${key}=${value}`;

    return typeof args === 'string' ? urlEnd : { ...args, url: urlEnd };
}

export default customQuery;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda