I have a strange problem and I'm sorry if I can't explain myself well
I created some state based on this example Handle an input with React hooks
cause I have multiple input fields in a child component and I want to pass this values
const [addressState, setAddressState ] = useState({
first_name: shipping.first_name,
last_name: shipping.last_name,
address1: shipping.address1,
address2: shipping.address2,
zip: shipping.zip,
province: shipping.province,
country: shipping.country,
phone: shipping.phone
});
on the onchange input I save the new value in another object cause I don't want save the state before confirm
const inputChangeHandler = (ev) => {
const { name, value } = ev.target;
newAddress[name] = value;
//setAddressState({ ...addressState, [name]: value }); //commented line, if I decomment this line, the states are correcty updated
}
So I launch this function at submit button
const confirmChangeAddress = (ev) => {
console.log("CONFERMA CAMBIO");
//newAddress is an object with the same key and correct values
for (let key in newAddress) {
const name = key;
const value = newAddress[key]
console.log(name, value)
setAddressState({ ...addressState, [name]: value });
}
}
I can assure that the name and value are identical at the data on commented line on inputChangeHandler, but the setAddressState in the loop have not effect (and no error is raised)
I can't imagine what's happening
newAddresssaved? It would be undefined in each of those code blocks you have. Edit your question to include that info....addressStatein each loop iteration, it does not include the updates you just made to addressstate in the previous loop iterations with the same event handler invocation.setAddressState((prev) => {...prev, [name]: value} )though I think the entire loop is not needed anyway as the wholeforloop could be replaced withsetAddressState((prev) => { ...prev, ...newAddress });and itd have the exact same effect as your intention.