2

i want to create state like this:

componentWillReceiveProps(nextProps) {
    nextProps.columns.forEach((c) => {
      const name = nextProps.columns[nextProps.columns.indexOf(c)];
      this.setState({ `${name}`: (this.props.activeHeaders.indexOf(c) > -1) });
      console.log(`${name}`);
    });
  }

I am mapping on my array columns, so each item on the array, i want to set state on them as key, is there a possibe way?

2 Answers 2

2

Is there a possible way?

Yes, but the way you are trying is not correct, instead of calling setState inside loop, first prepare an object with all the key-value, then pass that object to setState.

Like this:

componentWillReceiveProps(nextProps) {
    let obj = {};

    nextProps.columns.forEach((c, i) => {
        const name = nextProps.columns[nextProps.columns.indexOf(c)];
        obj[name] = this.props.activeHeaders.indexOf(c) > -1;
    });

    this.setState(obj);
}

Didn't get the meaning of this line:

const name = nextProps.columns[nextProps.columns.indexOf(c)];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. it worked. this is a good way to achieve what i wanted to do
2
componentWillReceiveProps(nextProps) {
    nextProps.columns.forEach((c) => {
      const name = nextProps.columns[nextProps.columns.indexOf(c)];
      this.setState({ [name]: (this.props.activeHeaders.indexOf(c) > -1) });
      console.log(`${name}`);
    });
  }

This should do the job

2 Comments

hmm, is that an array? [name]?
stackoverflow.com/questions/19837916/… read this this is how you can add dynamic keys to object in es6

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.