Home > Enterprise >  how to use modifier function with typescript in array
how to use modifier function with typescript in array

Time:10-18

I tried to update my Todos I doesn't work.
I don't know what I did I made a mistake.

ERROR in src/components/ToDoList.tsx:18:14
TS2345: Argument of type '(oldToDo: ItoDoForm[]) => (string | ItoDoForm)[]' is not assignable to parameter of type 'SetStateAction<ItoDoForm[]>'.
  Type '(oldToDo: ItoDoForm[]) => (string | ItoDoForm)[]' is not assignable to type '(prevState: ItoDoForm[]) => ItoDoForm[]'.
    Type '(string | ItoDoForm)[]' is not assignable to type 'ItoDoForm[]'.
      Type 'string | ItoDoForm' is not assignable to type 'ItoDoForm'.
        Type 'string' is not assignable to type 'ItoDoForm'.
    16 |     setValue("toDo", "");
    17 |     console.log(value.toDo);
  > 18 |     setToDos((oldToDo) => [value.toDo, ...oldToDo]);
       |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    19 |   };



import { useState } from "react";
    import { useForm } from "react-hook-form";
    
    interface Iform {
      toDo: string;
      value: string;
    }
    
    interface ItoDoForm {
      toDo: string;
    }
    function TodoList() {
      const { register, handleSubmit, setValue } = useForm<Iform>();
      const [toDos, setToDos] = useState<ItoDoForm[]>([]);
      const onSubmit = ({toDo}: Iform) => {
        setValue("toDo", "");
        console.log(toDo);
       
    
        **setToDos((oldToDo) => [toDo, ...oldToDo])**
//this setToDos doesn't work
    
      };
      return (
        <>
          <form onSubmit={handleSubmit(onSubmit)}>
            <input
              type='text'
              {...register("toDo", {
                required: "Please type what to do.",
                minLength: {
                  value: 2,
                  message: "at least type a word",
                },
              })}
              placeholder='Write what you want to do.'></input>
            <button>Click</button>
          </form>
          <ul></ul>
        </>
      );
    }
    
    export default TodoList;

CodePudding user response:

you use a different type for Todos state and toDo in submit function. Please use the same type. As you are assign a string to an object's array.

CodePudding user response:

This is because of the destructuring happening in the argument of the onSubmit function, resulting in toDo being just a string, where toDos needs an object.

One way to solve this is to put that toDo string back inside an object that will then match the type ItoDoForm:

setToDos((oldToDo) => [{ toDo }, ...oldToDo])
  • Related