Reputation: 59
how can this code be improved?
const [formData, setFormData] = useState({});
const setFormFieldValue = (name, value) => {
let newValues = {};
newValues[name] = value;
setFormData({...formData, ...newValues})
}
Upvotes: 0
Views: 42
Reputation: 7193
This might work inappropriately sometimes as the value in formData may not be updated as the rendering cycle is still remaining.
If you are supposed to use the latest state and update the state with the new state then you have to access the previous State.
For Example:
const [formData, setFormData] = useState({});
const setFormFieldValue = (name, value) => {
let newValues = {};
newValues[name] = value;
setFormData(prevFormData => {...prevFormData, ...newValues})
}
Upvotes: 1