New to React. I have a NewItem
component that should be pretty simple (and I have managed to do similar stuff before without problems): it has a form with two input text fields and it should update a stateful object (I think that's what it's called) when the form is submitted. Yet the state is updated only the second time the user submit the form. Why is that and how can I fix this? (Again, I am aware it's probably a very silly thing to ask, but I have done similar stuff with arrays and thought I got it).
Thank you for your patience and help. Here's the component:
import { useState } from "react";
const NewItem = () => {
const [newName, setNewName] = useState("");
const [newType, setNewType] = useState("");
const [newItem, setNewItem] = useState({ name: "", type: "" });
const getNewName = (event) => {
const changedName = event.target.value;
setNewName(changedName);
};
const getNewType = (event) => {
const changedType = event.target.value;
setNewType(changedType);
};
const handleSubmit = (event) => {
event.preventDefault();
const toAdd = { ...newItem, name: newName, type: newType };
setNewItem(toAdd);
console.log(toAdd);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name
<input type="text" value={newName} onChange={getNewName} />
</label>
<label>
Type
<input type="text" value={newType} onChange={getNewType} />
</label>
<button type="submit">Add</button>
</form>
);
};
export default NewItem;