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

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Accept an empty string as the defaultValue, but disallow it during validation using Zod, react-hook-form, and Material UI

Currently, I am working with material ui components alongside react-hook-form and zod validation in my project. One of the challenges I encountered is with a select field for a bloodType: const bloodTypes = [ "A+", "A-", "B+", ...

The button event listener in React fails to trigger without a page refresh

Within my index.html file, I have included the following code snippet: <head> ... <script type="text/javascript" src="https://mysrc.com/something.js&collectorId=f8n0soi9" </script> <script ...

Passing a method from a component to a service in Angular 9

Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply. The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then callin ...

How to modify a specific property of an array object in JavaScript

I have an array of objects that looks like this: [ { number: 1, name: "A" }, { number: 2, name: "e", }, { number: 3, name: "EE", } ] I am looking for a way to insert an object into the array at a specific position and ...

Guide on implementing a cordova plugin in a TypeScript cordova application

In my Cordova project, which utilizes Angular and Typescript, I am facing issues with implementing the juspay-ec-sdk-plugin for Cordova. I have explored possible solutions on StackOverflow related to integrating Cordova plugin in an Angular 4 Typescript ...

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

What is the procedure for cancelling a file upload in the FileUpload component of PrimeNG?

1. Issue Overview Looking to terminate file upload in PrimeNG's FileUpload component when certain filename patterns are detected. Using Angular 6.0.7 and PrimeNG 6.0.2. 2. Initial Strategy 2.1. HTML Code <p-fileUpload #fileUploader name="file" ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

The combination of Object.keys() and the find function

Having trouble figuring out why I'm getting an error when attempting to use ES6 .find on the following data in order to retrieve the record with id number 3. { {id:10,title:'Dairy & Eggs'} {id:7,title:'Laundry & Household'} {id ...

It seems like the recent upgrade to yarn 2 has caused issues with typescript types, whereas the installation of the same project with yarn 1 was

Recently, I've been attempting to update a typescript monorepo to utilize yarn 2, but I've encountered an issue where typescript is struggling to recognize certain react props. This functionality was working fine in yarn 1.x, leading me to believ ...

An automatic conversion cannot handle spaces and prohibited characters in Object keys

The AlphaVantage API uses spaces and periods in the keys. Their API documentation is not formal, but you can find it in their demo URL. In my Typescript application, I have created data structures for this purpose (feel free to use them once we solve the ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Can TypeScript be set up to include undefined as a potential type in optional chains?

Today, I encountered a bug that I believe should have been caught by the type system. Let me illustrate with an example: function getModel(): Model { /* ... */ } function processModelName(name: string) { return name.replace('x', 'y& ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

Using import statement is mandatory when loading ES Module in TS Node: server/src/index.ts

Attempting to kickstart a TypeScript Node project, I've gone ahead and added some essential dependencies (TypeScript, ESLint, Mongoose, and GraphQL). However, upon executing the command: ts-node-dev --respawn --transpile-only src/index.ts An error me ...