0

i have object in my state and nested object inside parent object, and updating objects in state may cause state mutating and lots of answers adviced to use immutability-helpers, (react-addons-update) this is my state:

    this.state = {
        room: {
            isOpen: false,
            index: '',
            roomNumber: '',
            reserved: '',
            isLux: null,
            _id: '',
            reserver:{
               name: '',
               surname: '',
               national_id: '',
               customer_number: '',
               staying_til: '',
               _id: ''
            }

        }
    }

and this is how update room properties:

roomChangeEvent(e){
       update(this.state, {
            room: {
               [e.target.name]: {$set: e.target.value}

            }
       })
}

and reserver properties

changeEvent(e){
        update(this.state, {
            room: {
                reserver: {
                  [e.target.name]: {$set: e.target.value}
                }

            }
       })
}

but it is not updating state even though it is getting value and name. what is problem?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
iLiA
  • 3,053
  • 4
  • 23
  • 45

1 Answers1

0

I would say, use immer-js https://immerjs.github.io/immer/docs/produce

This is very simple and no api to learn like in case of immutability-helpers, $push, $set etc.

Here is example from their page

import produce from "immer"

const baseState = [
    {
        todo: "Learn typescript",
        done: true
    },
    {
        todo: "Try immer",
        done: false
    }
]

const nextState = produce(baseState, draftState => {
    draftState.push({todo: "Tweet about it"})
    draftState[1].done = true
})

In your scenario

import produce from "immer"

changeEvent(e){
   this.setState(produce(draftState => {
      draftState.room.reserver[e.target.name] = e.target.value;
   }););
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • No need to take the state in the React example, just use the [curried `produce` function](https://immerjs.github.io/immer/docs/example-setstate). – Emile Bergeron Oct 22 '19 at 19:14
  • Though, it's the same amount of code without the _immer_ lib, so I'd say to anyone to just learn how to do immutable changes in JS, there's a lot of resources already and it's not that hard in the end. – Emile Bergeron Oct 22 '19 at 19:15
  • @EmileBergeron Thanks for sharing knowledge – Zohaib Ijaz Oct 22 '19 at 19:16