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?

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

2 Answers2

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

simbathesailor
  • 3,681
  • 2
  • 19
  • 30
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)];
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142