0

I'm trying to code "blockchain" visual implementation in React. I want to hold somehow inside array of objects(that are my blocks) index of each object. I can't figure out how to do it.

    this.state = {
      value: '',
      blocks: [{
        hash: calculateHash(1),
        timestamp: timeStamp(),
        dataOfBlock: 'Genesis Block',
        nounce: 607,
        index: 0
      }]
    }
  };

    addBlock = (event) => {
      event.preventDefault();

      this.setState({
      blocks: [...this.state.blocks, {
        hash: 'cos',
        timestamp: timeStamp(),      
        dataOfBlock: this.state.value,
        nounce: '',
        index: 1 // here's the problem
      }]
    })
    }

My code mimics what i want to accomplish where the comment is. I want to constantly add +1 to my index with each block.

3
  • 1
    if your always adding to the end of the array, you can make index this.state.blocks.length because the length of the prev array will be the index point of the new block Commented Feb 5, 2019 at 17:59
  • 2
    index: this.state.blocks.length+1, suggestion: use prevState instead of this.state inside setState. Commented Feb 5, 2019 at 17:59
  • my god, that was so easy, thanks Commented Feb 5, 2019 at 18:01

1 Answer 1

4

You can use length as index of new object when adding new object
Note: this.state.blocks.length will the next index because index start from 0

blocks: [...this.state.blocks, {
        hash: 'cos',
        timestamp: timeStamp(),      
        dataOfBlock: this.state.value,
        nounce: '',
        index: this.state.blocks.length
      }]
Sign up to request clarification or add additional context in comments.

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.