'React: "toISOString is not a function"
I am coding a Todo List with Next.js. I want to implement a dueDate function, if I make the post request, I get this error:
Unhandled Runtime Error
TypeError: dueDate.toISOString is not a function
I dont know how I can fix this, it would be nice if anyone can help me :)
My code:
const [newTodo, setNewTodo] = useState<any>({
title: "",
description: "",
})
const [dueDate, setDueDate] = useState<Date>(new Date())
const addTodo = () => {
axios.post("http://localhost:5000/todos", {
title: newTodo.title,
description: newTodo.description,
dueDate: dueDate.toISOString().slice(0, 10)
}).then(res => {
setTodos([...todos, res.data])
setNewTodo({
title: "",
description: "",
dueDate: "",
})
})
}
<input className="dueDate" type="date" onChange={(e) => setDueDate(e.target.value)} />
Solution 1:[1]
The problem is that input calls setDueDate passing e.target.value that is a string and not a Date, and you know that:
The "toISOString is not a function" error occurs when the toISOString() method is called on a value that is not a date object.
To solve this it's just necessary to modify input's onChange:
<input className="dueDate" type="date" onChange={(e) => setDueDate(new Date(e.target.value))} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giovanni Esposito |
