React: problem with putting object into "useState"
could you please help me, I add the ability to edit the date after adding. I get obj in TraningForm from TraningApp. I want to put this object into "useState", but for some reason this moment ignored. Although this object may be in the props, and I can get it safely:
Could you please explain to me what did I do wrong?
Code: https://github.com/tati-simonenko/22
You pass the obj
property as the initial state: useState(obj)
. Thus the form
state is only set once.
const [form, setForm] = useState(obj);
Update the form
state whenever the obj
property changes.
const [form, setForm] = useState(obj);
useEffect(() => setForm(obj), [obj]);
There were two issues in your code.
- In
TraningForm
form should be updated wheneverobj
changes. Need to add auseEffect
hook below.
useEffect(() => {
setForm(obj);
}, [obj]);
- In
EditObj
method there was a mistake. It should be...item
instead of...prevTraining
.
const EditObj = (obj) => {
setTraining((prevTraining) =>
prevTraining.map((item) => {
if (item.id == obj.id)
return { ...item, date: obj.date, passed: obj.passed };
return item;
})
);
};
Code Sandbox