Home > Back-end >  How can I dynamically update values in an object state?
How can I dynamically update values in an object state?

Time:12-17

I have an object, data, in my state. I have an array of keys, keysToUpdate, and an array of values, newValues, to update.

const [data, setData] = useState({
    firstName: "",
    lastName: "",
    age: "",
    address: "",
    email: "",
})

const keysToUpdate = ["firstName", "lastName"];
const newValues = ["Joe", "Smith"];

Is there a way to dynamically update the data with setState even if I don't know what the fieldsToUpdate array contains?

CodePudding user response:

Sure, like so:

const newData = {...data}
keysToUpdate.forEach((key, i) => newData[key] = newValues[i])
setData(newData)

CodePudding user response:

Nevermind, I realized how simple of an answer this is. You can simply iterate through the keysToUpdate array and call setData on each iteration.

const updateKeys = (keysToUpdate, newValues) => {
    keysToUpdate.forEach((key, i) => {
        setData(prevData => {
            return {
                ...prevData,
                [key]: newValues[i]
            }
        })
    })
}

CodePudding user response:

you could use this concept to figure out a solution for you, this in case you want to update state using input for instance.

const [data, setData] = useState({
    name: '',
    age:''
});


const onInputChange = ({target:{name, value}}) =>{

    setData({
        ...data,
        [name]: value
    });
    
}
  • Related