Search code examples
reactjsreact-hookstanstackreact-query

Property 'mutate' does not exist on type '() => Promise<[]>'


I'm trying to use Tanstack Query to post datas by using useMutation hook, but it dosen't seem to work. Can you please help me with my code ? I'm new to the dev world so thank you for your help.

I'm using a service file :

import axios from "axios"; import { UserData, UsersData } from "../types/userDatas";

const BACK_URL = "http://localhost:5000";

const UserService = { get: (): Promise<UsersData> => axios.get(${BACK_URL}/users).then((res) => res.data), post: (inputData: UserData): Promise<UsersData> => axios.post(${BACK_URL}/users, inputData).then((res) => res.data), };

export default UserService;

I have an error on the mutate, I don't know how to fix it.

const AddUser = () => {
  const [inputData, setInputData] = useState<UserData>({
    lastName: "",
    firstName: "",
    email: "",
    icons: "",
  });

  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  //MUTATION
  const NewUsers = (): Promise<UsersData> => UserService.post(inputData);

  const { data, isSuccess, isError } = useMutation({
    mutationFn: NewUsers,
    retry: false,
  });

  const onSubmit = async (event: { preventDefault: () => void }) => {
    handleClose();
    event.preventDefault();
    NewUsers.mutate({ inputData });
  };```

Solution

  • The mutate function is something that's returned by useMutation. It's not a property of NewUsers:

    const NewUsers = (): Promise<UsersData> => UserService.post(inputData);
    
    const { data, isSuccess, isError, mutate } = useMutation({
      mutationFn: NewUsers,
      retry: false,
    });
    
    const onSubmit = async (event: { preventDefault: () => void }) => {
      handleClose();
      event.preventDefault();
      mutate();
    };
    

    Note: with the way you've defined your mutationFn, you do not pass any arguments in when you call mutate(). mutate will call NewUsers passing in no arguments, which will call UserService.post(inputData). Passing in your own input data would have no effect, since NewUsers would ignore it.

    Alternatively, you could have done the following, in which case you would pass the data in when calling mutate:

    const { data, isSuccess, isError, mutate } = useMutation({
      mutationFn: UserService.post,
      retry: false,
    });
    
    const onSubmit = async (event: { preventDefault: () => void }) => {
      handleClose();
      event.preventDefault();
      mutate(inputData);
    };