I was trying to reset my input fields to a state variable but I keep getting this error. I'm not exactly sure why this uncontrolled input to controlled input error is happening because I've written a non typescript react application by using the value={(some state variable)} before in order to aid in resetting an input field.
react_devtools_backend.js:4026 Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
at input
at div
at div
at div
at App (http://localhost:3000/main.adbc9122bd735b7bde3e.hot-update.js:31:74)
This is my code:
import React, {FC, ChangeEvent, useState} from 'react';
import './App.css';
import {ITask} from './Interfaces'
const App: FC = () => {
const [task, setTask] = useState<string>("");
const [deadline, setDeadline] = useState<number>(0);
const [todoList, setTodoList] = useState<ITask[]>([]);
const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
if (event.target.name === task) {
setTask(event.target.value);
}
setDeadline(Number(event.target.value))
}
const addTask = (): void => {
const newTask = {taskName: task, deadline: deadline}
setTodoList([...todoList, newTask])
console.log(todoList)
setTask("")
setDeadline(0)
}
return (
<div className="App">
<div className="header">
<div className="inputContainer">
<input type="text"
name="task"
value={task}
placeholder="Task..."
onChange={handleChange} />
<input type="number"
name="deadline"
value={deadline}
placeholder="Deadline (in days)..."
onChange={handleChange} />
</div>
<button onClick={addTask}>Add Task</button>
</div>
<div className="todoList">
</div>
</div>
);
}
export default App;
CodePudding user response:
is this your actual and complete code? If so you probably want to check for "task" not task in handleChange, while also making sure you only set the deadline if the input does not come from the task input.
const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
if (event.target.name === "task") {
setTask(event.target.value);
} else {
setDeadline(Number(event.target.value));
}
}
CodePudding user response:
const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
if (event.target.name === "task") {
setTask(event.target.value);
} else {
setDeadline(Number(event.target.value))
}
}
Set the target.name
evaluation to a string and add an else statement to prevent the second input from always being updated.