Home > Software engineering >  react component not updated after state update
react component not updated after state update

Time:12-22

I have an grid composed of lines. Each line has :

  • a number input filled by the user (amountWithoutTaxe)
  • a number label that should be automatically calculated after the previous one has been filled (amountWithTaxe) and that equals to thrice the previous one.

What I expect : The user increases or decreases the first field and automatically the second one is updated. Example : I put 2, then 6 is automatically displayed.

What I get : The user increases or decreases the first field, the second one is only updated after he clicks on "add a line". Example : I put 2, nothing is updated, I click on "add a line", then the field is updated.

This is the playground https://codesandbox.io/s/react-tsx-playground-forked-bss6sh?file=/src/index.tsx

I dont understand why its not working as expected, as the state is refreshed after the first input changes

CodePudding user response:

It seems you are trying to do some changes on the state itself without the setLines function. If you change the attributes of lines that way, React does not know it needs to render, it needs to get a new array. The fix for this can be that in your onChange function you make a new variable called let newLines = [...lines] for example and do changes on it, then set newLines.

For your input element please consider the following change

    <input
      type="number"
      value={line.amountWithoutTaxe}
      onChange={(event) => {
        let newLines = [...lines];
        newLines[index].amountWithoutTaxe = event.target.valueAsNumber;
        newLines[index].amountWithTaxe =
          newLines[index].amountWithoutTaxe * 3;
        setLines(newLines);
      }}
    ></input>
  • Related