-1

I am trying to pass a string to a query in Redux Toolkit (TypeScript)

    foo: builder.query<FooResponse, void>({
       query: (bar) => ({ // bar gets automatically the type QueryArg assigned
           url: SOME_URL_CONSTANT,
           params: {bar}
       }),
        transformResponse(response: FooResponse[]): FooResponse{
           return response[0]
        }
    }),

When I am calling

useFooQuery("whatever")

The TypeScript compiler complains

Argument of type '"whatever"' is not assignable to parameter of type 'void | unique symbol'. When I try to change

query: (bar: string) => ({...

I get

Type '(bar: string) => { url: string; params: { bar: string; }; }' is not assignable to type '(arg: void) => string | FetchArgs'.   Types of parameters 'bar' and 'arg' are incompatible. Type 'void' is not assignable to type 'string'.

So, how do I pass a parameter to the query function?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
four-eyes
  • 10,740
  • 29
  • 111
  • 220

1 Answers1

0

"@reduxjs/toolkit": "^1.9.5"

builder.query<ResultType, QueryArg>(), since you passing a string to useFooQuery('whatever'), the QueryArg generic parameter should be string type, not void. See Typing query and mutation endpoints

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

type FooResponse = any;

export const fooApi = createApi({
  reducerPath: 'foo',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://localhost:3000/api/v2/' }),
  endpoints: (builder) => ({
    foo: builder.query<FooResponse, string>({
      query: (bar) => ({
        url: `foo`,
        params: { bar },
      }),
    }),
  }),
});

import React from 'react';

export const App = () => {
  fooApi.useFooQuery('whatever');
  return <div>App</div>;
};
Lin Du
  • 88,126
  • 95
  • 281
  • 483