reactjsaxiostanstackreact-query

Having typscript error within my code when creating an POST function using tanstack/react-query


I'm doing my first project using react, and I ran into some problem with POST function from an external library

Here's my code breakdown:

"use client";
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import React from "react";

export default function CreatePost() {
  const [title, setTitle] = useState("");
  const [isDisabled, setIsDisabled] = useState(false);

  //Create a Post
  const { mutate } = useMutation(
    async (title) => await axios.post("/api/posts/addPost", { title });
    
  return (
    <form className="bg-white my-8 p-8 rounded-md">
      <div className="flex flex-col my-4">
        <textarea
          onChange={(e) => setTitle(e.target.value)}
          name="title"
          value={title}
          placeholder="What's on your mind?"
          className="p-4 text-lg rounded-md my-2 bg-gray-200"
        ></textarea>
      </div>
      <div className="flex items-center justify-between gap-2">
        <p
          className={`font-bold text-sm ${
            title.length > 300 ? "text-red-700" : "text-grey-700"
          }`}
        >{`${title.length}/300`}</p>
        <button
          disabled={isDisabled}
          className="text-white text-sm px-6 py-2 rounded-xl bg-teal-600 disabled:opacity-25"
          type="submit"
        >
          Create a Post
        </button>
      </div>
    </form>
  );
}

The problem occured at line 13: async (title) => await axios.post("/api/posts/addPost", { title }); Giving an error of: Type '(title: any) => Promise<AxiosResponse<any, any>>' has no properties in common with type 'UseMutationOptions<unknown, Error, void, unknown>'.ts(2559)

I tried having an mutation file on its own such as:

import { useMutation } from 'react-query';
import axios from 'axios';

const useAddPost = () => {
  return useMutation(
    async (title: string) => {
      return await axios.post("/api/posts/addPost", { title });
    },
    {
      // You can provide additional options here, like onSuccess, onError, etc.
      onSuccess: (data) => {
        console.log('Post added successfully:', data);
      },
      onError: (error) => {
        console.error('Error adding post:', error);
      }
    }
  );
};

export default useAddPost;

Still no luck...


Solution

  • I suspect you are working from an older tutorial or documentation. The current V5 React-Query useMutation hook consumes an options object, not an asynchronous function.

    const {
      data,
      error,
      isError,
      isIdle,
      isPending,
      isPaused,
      isSuccess,
      failureCount,
      failureReason,
      mutate,
      mutateAsync,
      reset,
      status,
      submittedAt,
      variables,
    } = useMutation({
      mutationFn,
      gcTime,
      meta,
      mutationKey,
      networkMode,
      onError,
      onMutate,
      onSettled,
      onSuccess,
      retry,
      retryDelay,
      scope,
      throwOnError,
    })
    

    Update to pass the fetching function as the mutation's mutationFn property.

    const { mutate } = useMutation({
      mutationFn: (title) => axios.post("/api/posts/addPost", { title }),
      onSuccess: (data) => {
        console.log('Post added successfully:', data);
      },
      onError: (error) => {
        console.error('Error adding post:', error);
      },
    });