I’m trying to save the value of the input field to state. When the defaultValue is ‘projectName’, and I delete the word ‘Name’ from the input field, I want the state to update so that the defaultValue is ‘project’. When I console.log e.target.value in the onChange, I can see the change happening when I make the deletion, and my code in the onChange is saving the value to state, but unfortunately, the state does not update. Any thoughts as to why?
Here is a Code Sandbox: https://codesandbox.io/s/amazing-river-o15h4?file=/src/Child.js
… And here is a screenshot of the console.log in the onChange and the setState call not updating:
App.js
import "./styles.css";
import Child from "./Child";
export default function App() {
const thisIsState = {
id: 1,
projectName: "projectName",
description: "description"
};
return (
<div className="App">
<Child project={thisIsState} />
</div>
);
}
Child.js
import { useState, useEffect } from "react";
import "./styles.css";
export default function Child(props) {
console.log(props);
const [state, setState] = useState({
projectName: "",
description: ""
});
let project = props.project;
let errors = props.errors;
useEffect(
(state) => {
setState({
...state,
projectName: project.projectName,
description: project.description
});
console.log("useEffect1 state: ", state);
},
[project, errors]
);
const onChange = (e) => {
console.log("e.target.value in onChange: ", e.target.value);
setState((state) => ({
...state,
[e.target.name]: e.target.value
}));
console.log("onChange() state: ", state);
};
return (
<div className="App">
<form>
<input
type="text"
placeholder="Project Name"
name="projectName"
defaultValue={props.project.projectName}
onChange={onChange}
style={{ marginBottom: "15px" }}
/>
<br />
<input
type="text"
placeholder="Project Name"
name="projectDescription"
defaultValue={props.project.description}
onChange={onChange}
/>
</form>
</div>
);
}