-3

I've been trying to create states for my application. Basically I have apples which have ID and Status. So my code is:

constructor(props){
    super(props);
    this.state = {
      apples: [],
      treeState: ''
    }
  }

  componentWillMount(){
    this.setState(
      {
        apples: [
      {
        id: '1',
        status: 'present'
      },
      {
        id: '2',
        status: 'present'
      },
      {
        id: '3',
        status: 'present'
      }
    ],
  treeState: 'stagnant'});
  }

At some point I'll have ten or twelve apples. And creating them manually is both line consuming and not efficient. I need a for loop but couldn't find any useful one online. This one was promising but cannot implement it to my code. Also I have an another state that I called "treeState". So creating an apple loop with ID's plus adding the treeState at the end is my goal.

Thanks.

devserkan
  • 16,870
  • 4
  • 31
  • 47
Ufuk Ozdogan
  • 13
  • 1
  • 8

1 Answers1

1

You can use Array.from with its mapping callback to create as many apples as needed; here's an example with 12:

componentWillMount(){
  this.setState({
    apples: Array.from({length: 12}, (_, index) => ({id: index + 1, status: 'present'})),
    treeState: 'stagnant'
  });
}

Or if you prefer, a simple for loop:

componentWillMount(){
  const apples = [];
  for (let id = 1; id <= 12; ++id) {
      apples.push({id, status: 'present'});
  }
  this.setState({
    apples,
    treeState: 'stagnant'
  });
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you so much Mr. Crowder! Both of them are working flawlessly. I'm new to JavaScript and React and the first one has some really complicated but awesome syntax. – Ufuk Ozdogan Oct 17 '18 at 17:51