0

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

7
  • Needs more info: where is newAddress saved? It would be undefined in each of those code blocks you have. Edit your question to include that info. Commented Apr 11 at 16:55
  • Sorry, I Will update on monday, but newaddress is declared in the same file, and more important contain the correct data (printed with console log, before set the state). Next week I will try to set up a demo on codepen Commented Apr 11 at 17:04
  • 1
    Your issue is summarised here react.dev/learn/queueing-a-series-of-state-updates. React state updates are not immediate. They are queued for next rerender. When you spread ...addressState in 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. Commented Apr 11 at 19:24
  • Simplest change is to change the set call inside the loop to setAddressState((prev) => {...prev, [name]: value} ) though I think the entire loop is not needed anyway as the whole for loop could be replaced with setAddressState((prev) => { ...prev, ...newAddress }); and itd have the exact same effect as your intention. Commented Apr 11 at 19:27
  • Thanks @adsy for the link, it looks like my problem! However the syntax of your solutions is wrong. I'm trying to solve. Commented Apr 14 at 7:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.