Home > database >  How to change properties of sub-objects in React JS
How to change properties of sub-objects in React JS

Time:08-08

I have this function that is called using the onChange property of an input field. The first console.log below reflects the changed value correctly. The second one does not.

I've tried deep copying newDisplayedAssignment and then changing the property. Didn't work. Any advice would be greatly appreciated!

--- New to React JS

function onDateChange(event, newDisplayedAssignment, key, assignment) {
    newDisplayedAssignment[key][assignment]['date'] = event.target.value;
    console.log(newDisplayedAssignment[key][assignment])
    console.log(newDisplayedAssignment[key])
    return newDisplayedAssignment;
}

CodePudding user response:

React doesn't see changes because you have the same reference to the object.

Changing the reference should fix the issue

return { ...newDisplayedAssignment }

CodePudding user response:

It looks like you need to modify deep objects but it seems difficult and the code is inelegant,

There is a solution here (need to introduce a library)

I really want you to take 5 minutes to look at this library immer

Example

const deepObj = {
  first: {
    a: 'a',
    b: {
      bObj: {
        isAnimal: false,
        isBig: true
      }
    }
  }
}

// Now, let's try to modify the attribute of isAnimal
// Old way: is ugly
setOs({
  first: {
    ...deepObj.first,
    b: {
      ...deepObj.first.b,
      bObj: {
        ...deepObj.first.b.bObj,
        isAnimal: true
      },
    },
  },
})


// use Immer: It's great, isn't it ? 
import produce from "immer"

setOs({
  ...produce(deepObj, draft => {
    draft.first.b.bObj.isAnimal = true
  })
})


  • Related