skip to Main Content

this props.update is giving the error described in the title

import { useState } from "react";
import axios from "axios";
import { todoType } from "../../types/todo";
type sendResponse = {
  task: string;
};
type getResponse = {
  data: {
    message: string;
    newTodo: todoType;
  };
};
type updateTodosInterface = {
  updateTodos: (prev: todoType[]) => todoType[];
};
export const InputBar: React.FC<updateTodosInterface> = (props) => {
  const [searchInput, setSearchInput] = useState("");
  const inputHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchInput(event.target.value);
  };
  const addTodo = async () => {
    const { data } = await axios.post<sendResponse, getResponse>(
      "http://localhost:3000/api/v1/todo/create",
      { task: searchInput }
    );
    console.log(data.newTodo);
    **props.updateTodos((prev: todoType[]) => [...prev, data.newTodo]);**
  };
  return (
    <div className="flex gap-2 justify-center">
      <input
        type="text"
        placeholder="Add a task"
        value={searchInput}
        onChange={inputHandler}
        className="p-2 rounded-md w-10/12 focus: outline-none"
      />
      <button
        onClick={addTodo}
        className="px-2 py-3 bg-black text-white rounded-md"
      >
        Add Task
      </button>
    </div>
  );
};

I want to update my todo state which is an array of todoType. I passed the setter function as a prop and am trying to append the new value. However the props. update is giving the error that it is not assignable. I’ve already tried all GPT and Copilot and they’re giving me the same response that I have written

2

Answers


  1. You wrote:

    type updateTodosInterface = {
      updateTodos: (prev: todoType[]) => todoType[];
    };
    

    This means that updateTodos should be a function expecting a prev array as argument, that returns an array.

    You are using it like:

    props.updateTodos((prev: todoType[]) => [...prev, data.newTodo]);
    

    I.e. by passing a function as an argument.

    Solution: update your type to be:

    type UpdateTodos = (prev: todoType[]) => todoType[];
    
    type updateTodosInterface = {
      updateTodos: (updater: UpdateTodos) => void;
    };
    
    Login or Signup to reply.
  2. You need to update the type to this

    type updateTodosInterface = {
      updateTodos: React.Dispatch<React.SetStateAction<todoType[]>>;
    };
    

    Also in the parent component of InputBar, where you are passing the props, make sure its the setTodos function.

    const ParentComponent = () => {
      const [todos, setTodos] = useState<todoType[]>([]);
      ...
      return (
        ...
        <InputBar updateTodos={setTodos} />
        ...
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search