Олег Клишин
Олег Клишин

Reputation: 59

Best path to update JS state object in react

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

Answers (1)

Jignesh Mayani
Jignesh Mayani

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

Related Questions