skip to Main Content

I want to create subscribe form page and I use next js, react-query, typescript. I can not configurate my API request in typescript.

My form component

'use client';
import React, { FormEvent, useState } from 'react';

import { useEmailSubscription } from 'src/api/email-subscription/mutations';

const SubscribeForm = () => {
  const [email, setEmail] = useState('');
  const { mutate } = useEmailSubscription();

  const _onSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    mutate(email);
  };

  return (
    <form onSubmit={_onSubmit}>
      <div className="form-group">
        <label id="email">Stay tuned for an awesome experience!</label>
        <input
          type="email"
          id="email"
          onChange={(e) => setEmail(e.target.value)}
          placeholder="[email protected]"
        />
      </div>
      <button type="submit">Subscribe</button>
    </form>
  );
};

export default SubscribeForm;

My first error

mutate(email) // Argument of type 'string' is not assignable to parameter of type 'void'

My request

export const useEmailSubscription = () => {
  return useMutation((email: string) => axiosOpen.post('/email-subscriptions', { email }));
};

My second error

Type (email: string)=> Promise <AxiosResponse <any, any>> has no properties in common with type 'UseMutationOptions<unknown, Error, void, unknown'

I don’t know how can I fix it?

2

Answers


  1. First Error: mutate(email)

    Your mutate function is expecting a parameter of type void , but you are passing a string (email). This discrepancy is likely due to how you defined your mutation. In your useEmailSubscription hook, you need to properly type the mutation function.

    Second Error: Type Mismatch with useMutation

    You need to ensure that the type you specify in useMutation aligns with the function you’re passing.

    Change your mutation hook like this:

    export const useEmailSubscription = () => {
      return useMutation<void, Error, string>((email) => axiosOpen.post('/email-subscriptions', { email }));
    };
    

    The form component should work as is, with the mutate function correctly accepting a string argument

    Login or Signup to reply.
  2. The error says that you are passing a function where MutationOptions would be expected. I assume you are using v5 of React Query, where the only available syntax is to pass an options object to useQuery and useMutation. So you need:

    export const useEmailSubscription = () => {
      return useMutation({
        mutationFn: (email: string) => axiosOpen.post('/email-subscriptions', { email })
      })
    };
    

    calling mutate(email) is correct and the error should go away after that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search