-1

Is there any option to add zone without maping it and adding new object into state on first click?

https://codesandbox.io/s/charming-ellis-b7e8k?file=/src/App.js:319-324

My wanted behaviour is filling inputs and adding it into state on click. After added I will reset input to add more zones into state.

Someone told about using immer.js. Actually reading docs.. is there any other way?

Thank you

Jakub
  • 11
  • 3
  • Hi Brendan, I want to have inputs available without adding new object and when I fill inputs and click on "add" button I want it to be added into state. – Jakub Aug 02 '21 at 21:59

1 Answers1

0

useState will require objects to be immutable to detect changes. So, array.push will usually not have the desired effect. Create a new one instead:

onClick={() =>
  setZones([...zones, {
    Server: "",
    positionName: "",
    positionIdentification: ""
  }])
}

This will create a new array with the contents of the old plus the new content.

To avoid creating a new array every time, as you suggested immer can do that for you with the useImmer hook.

matthiasgiger
  • 1,086
  • 9
  • 17
  • Can you give me hint with immer please? My brain cant get it sadly.. I tried ```js const updateZone = useCallback((e, index) => { const { value, name } = e.target; setZones( produce((draft) => { draft[index] = {[name]: value } }) ); }) ``` But its meh, probably not having all params I need. – Jakub Aug 02 '21 at 22:09
  • You're almost there, try `setZones(produce(prevZones, draft => {..same as you..}))` or wrap the whole state with the useImmer hook. Hope this helps. – matthiasgiger Aug 02 '21 at 22:17
  • Sadly I wasn't successfull with both things. – Jakub Aug 02 '21 at 22:24