56

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?

2 Answers 2

89

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
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice find. Did not know about this ES6 feature. See the other answer for the more clumsy "old way".
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.