skip to Main Content

On the Form onSubmit function i am getting a typescript error that i am not able to understand how to fix – Promise-returning function provided to attribute where a void return was expected.eslint@typescript-eslint/no-misused-promises
const onSubmit: SubmitHandler<FormInput>

I’ve tried many solutions but the error isn’t going anywhere.

import { BiSearch } from "react-icons/bi";
import { useAppDispatch } from "../hooks";
import { useForm, SubmitHandler } from "react-hook-form";
import { setSearchQuery } from "../store/searchQuerySlice";

type FormInput = {
  searchQuery: string;
};

const SearchForm = () => {
  const dispatch = useAppDispatch();

  const { register, handleSubmit } = useForm<FormInput>();

  const onSubmit: SubmitHandler<FormInput> = (data, event) => {
    event?.preventDefault();
    const { searchQuery } = data;
    dispatch(setSearchQuery(searchQuery));
  };

  return (
    <>
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="flex justify-center items-center gap-3"
      >
        <input
          className="w-[75vw] h-12 px-3 bg-slate-200 rounded-md text-slate-800 outline-none text-lg"
          type="text"
          placeholder="Enter Search Term"
          {...register("searchQuery", { required: true, maxLength: 20 })}
        />
        <button
          className="text-2xl cursor-pointer bg-slate-300 p-3 rounded-md"
          type="submit"
        >
          <BiSearch />
        </button>
      </form>
    </>
  );
};

export default SearchForm;

2

Answers


  1. Try modify onSubmit function like this

    const onSubmit: SubmitHandler<FormInput> = (data, event) => {
      return new Promise<void>((resolve) => {
        event?.preventDefault();
        const { searchQuery } = data;
        dispatch(setSearchQuery(searchQuery));
        resolve();
      });
    };
    
    Login or Signup to reply.
  2. As per the understanding, You have to add a void keyword before dispatch call.

    const onSubmit: SubmitHandler<FormInput> = (data, event) => {
      event?.preventDefault();
      const { searchQuery } = data;
      void dispatch(setSearchQuery(searchQuery));
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search