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
You wrote:
This means that
updateTodos
should be a function expecting aprev
array as argument, that returns an array.You are using it like:
I.e. by passing a function as an argument.
Solution: update your type to be:
You need to update the type to this
Also in the parent component of
InputBar
, where you are passing the props, make sure its the setTodos function.