Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using immutability-helper in React to set variable object key

I have a function I want to write in React. In my class I have a state object fields that looks like this:

this.state = {   step: 1,   fields: {     type: '',     name: '',     subtype: '',     team: '',     agreement: ''   } }; 

I have various functions that assign those keys using immutability helper that generally look like:

assignType(attribute) {   var temp = update(this.state.fields, {     type: {$set: attribute}   });    this.setState({     fields: temp   }); } 

What I would like to do is use a function that's more generic and do something like this:

assignAttribute(field, attribute) {   var temp = update(this.state.fields, {     field: {$set: attribute}   });    this.setState({     fields: temp   }); } 

But, this doesn't work. What can I do to use a variable key using immutability-helper?

like image 626
Cassidy Avatar asked Feb 22 '17 23:02

Cassidy


People also ask

What is the use of immutability helper?

There is a helper function update from immutability-helper which eases the code involved in state updates. The function takes the original state object and another object which specify the state changes. The second parameter has the same hierarchy as the original state object.

Why states are immutable in react?

In React, using an Immutable state enables quick and cheap comparison of the state tree before and after a change. As a result, each component decides whether to re-rendered or not before performing any costly DOM operations.

What is react immutable?

Immutable. js allows us to detect changes in JavaScript objects/arrays without resorting to the inefficiencies of deep equality checks, which in turn allows React to avoid expensive re-render operations when they are not required. This means Immutable.


2 Answers

Figured it out! I needed to use ES6 computed property names and simply edit assignAttribute to:

assignAttribute(field, attribute) {   var temp = update(this.state.fields, {     [field]: {$set: attribute}   });    this.setState({     fields: temp   }); } 
like image 103
Cassidy Avatar answered Sep 21 '22 23:09

Cassidy


You can use the [] syntax if you have dynamic field names:

var data = {} data[field] = {$set: attribute}  var temp = update(this.state.fields, data) 

This gets a lot more concise if you can use ES6.

like image 30
Thilo Avatar answered Sep 23 '22 23:09

Thilo