Using React Query's useMutation hook may result in an error message of "No overload matches this call"

When incorporating react-query into my typescript project, I encountered a perplexing type error while attempting to utilize the useMutation() hook with a graphql query.

Here is an example of the code:

useMutation(
    async (
      parameter1: string,
      parameter2: string
    ) => {
      const response = await sdk.myMutation({
        parameter1: parameter1,
        parameter2: parameter2,
      });
      return response;
    },
    {
      onSettled: () => queryClient.invalidateQueries([CACHE_KEY]),
    }
);

The specific type error message reads as follows:

  No overload matches this call.
  Overload 1 of 4, '(mutationFn: MutationFunction<{ __typename: "IdResponse"; id: string; }, string>, options?: Omit<UseMutationOptions<{ __typename: "IdResponse"; id: string; }, unknown, string, unknown>, "mutationFn"> | undefined): UseMutationResult<...>', gave the following error.
    Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationFunction<{ __typename: "IdResponse"; id: string; }, string>'.
  Overload 2 of 4, '(mutationKey: MutationKey, options?: Omit<UseMutationOptions<unknown, unknown, void, unknown>, "mutationKey"> | undefined): UseMutationResult<unknown, unknown, void, unknown>', gave the following error.
    Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationKey'.
  Overload 3 of 4, '(mutationKey: MutationKey, mutationFn?: MutationFunction<unknown, void> | undefined, options?: Omit<UseMutationOptions<unknown, unknown, void, unknown>, "mutationFn" | "mutationKey"> | undefined): UseMutationResult<...>', gave the following error.
    Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationKey'.

Answer №1

It wasn't immediately clear to me, but the issue stemmed from my attempt to pass multiple parameters to the function used in useMutation.

The MutationFunction type only allows for a single parameter (referred to as variables in a confusing manner).

To resolve the issue, I passed an object containing my parameters to the function like this:

useMutation(
    async ({
      parameter1,
      parameter2
    }:{
      parameter1: string,
      parameter2: string
      }
    ) => {
      const response = await sdk.myMutation({
        parameter1: parameter1,
        parameter2: parameter2,
      });
      return response;
    },
    {
      onSettled: () => queryClient.invalidateQueries([CACHE_KEY]),
    }
);

A more organized approach would involve creating a type to store these parameters, something similar to this:

type myMutationParams ={
  parameter1: string;
  parameter2: string;
}

Subsequently, the useMutation hook would appear as follows:

useMutation(
    async ({
      parameter1,
      parameter2
    }: myMutationParams
    ) => {
      const response = await sdk.myMutation({
        parameter1: parameter1,
        parameter2: parameter2,
      });
      return response;
    },
    {
      onSettled: () => queryClient.invalidateQueries([CACHE_KEY]),
    }
);

Answer №2

It seems to be a common issue for me when working with callback functions such as onError, onSuccess, or onSettled.

  • Check for any unnecessary type assignments in parameters and fix any typing errors.

For instance:

// Incorrect usage
onSettled: (_, err: CustomError) => {
 
},
// Correct approach
onSettled: (_, err) => {
  const newErr = err as CustomError;
  // Now you can utilize the newErr
},

Validate types within mutationFn:

For example:

// Incorrect implementation
mutationFn: (accountId: string, accountDetails: Account) => {

},
// Correct method
type MutationParams = {
  accountId: string;
  accountDetails: Account;
};
mutationFn: (requestBody: MutationParams) => {
  // Destructure the param as needed.
},
  • Ensure that only one parameter is used by combining multiple parameters into an object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the formcontrolname property of a FormGroup within a FormArray

I am currently facing an issue with my code. In my FormGroup, I have a FormArray containing 3 FormControls. My goal is to iterate through the FormArray and display the values of each control in a form. However, I am unsure about what to use for the formCon ...

Encountering an Angular schematics issue while utilizing an external schematic ng-new, the specified version is

Attempting to develop a schematic that utilizes the angular ng-new as the initial call and another schematic to add a prettier file to the new project. Upon executing the command, an error is encountered: Data path "" must have required property 've ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Is there a way to retrieve the date of the most recent occurrence of a specific "day" in TypeScript?

Looking to retrieve the date (in YYYY-MM-DD format) for the most recent "Wednesday", "Saturday", or any user-specified day. This date could be from either this week or last week, with the most recent occurrence of that particular day. For instance, if toda ...

A guide to accessing a property value in Angular 6 from an object using a string key

In my Angular application, I am receiving an object with multiple arrays from a REST service. I need to access the value from the incoming object based on the property name. Here is what the object looks like: data{ array1:{}, array2:{}, array3:{} } Th ...

openapi-generator is generating subpar api documentation for TypeScript

Executing the command below to generate an auto-generated API using openapi-generator (v6.0.1 - stable): openapi-generator-cli generate -i app.json -g typescript -o src/main/api The json file is valid. Validation was done using openapi-generator-cli valid ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

Angular: "btn" class vanishes when the button is toggled

I am facing an issue with the button's class change functionality. I am using the [ngClass] directive to switch between Bootstrap classes for the button style. However, when I click the button, the "btn" class seems to disappear from the code. Instead ...

Using keyof to access static properties within TypeScript classes

While experimenting with this TypeScript playground code sample, I encountered an issue with defining the greeterBuilderName variable. How can I specify that I want properties of the Greeter function itself (such as prototype, warm_greeter, etc.) when keyo ...

Object data is not being received by the defaultValue in React Hook Form

I am currently utilizing React Hook Form to facilitate the process of editing/updating data. I retrieve my data from zustand with a value type of any, and then proceed to save it as the defaultValue in React Hook Form. However, when attempting to acquire v ...

Instantiate the component array upon object instantiation

I'm currently in the process of learning Angular 2, so please bear with me if this question seems trivial. I am attempting to create a dynamic form that can be bound to a model. However, I am encountering an issue where I am unable to initialize my ar ...

Is TypeScript to blame for the unexpected token error in Nock?

My code snippet in the ts file looks like this: nock('https://example.test').post('/submit').reply(200,{ "status": "Invalid", "message": "Invalid Request", }); However, when I try to ...

Guide: Populating an MUI Autocomplete TextField using data fetched from Axios

I have created a registration form for pets which includes an MUI Autocomplete component in the text field for selecting the pet type. However, I am facing an issue when trying to pre-fill the Autocomplete component with data from the database while edit ...

Exporting modules in TypeScript using "module.exports"

While working on my Yeoman generator, I initially wrote it in JavaScript like this: "use strict"; var Generator = require("yeoman-generator"); var chalk = rquire("chalk"); module.exports = class extends Generator { initializing() { this.log( c ...

Encountered Typescript issue when utilizing typed forms in Angular

Below is the interface I am working with: export interface ILoginDto { email: string; password: string; } Here is a snippet of the relevant code from the component: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; export ...

user interface grid element in Materia

After writing this code, I encountered the following error: No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; .. ...

RouterModule is a crucial external component that is essential for integrating

If I have a very simple component that is part of an Angular component library, it might look like this: mycomponent.module.html <div> <a routerLink="/"> </div> mycomponent.component.ts import { Component, OnInit, Input } from &a ...