0

I'm quite new to React and I'm trying to build the classic to do list! However, I'm struggling to track the array items.
I'm creating the items as follows:

     this.setState({item: {
      text: event.target.value,
      index: this.state.items.length++,
      completed:false
        }

And I've been adding to the array of items like this:

     this.setState({items:this.state.items.concat(this.state.item)});

But this method creates a new array every time, so I can't use the index of the item. However when I try using push to add to the array, I can't seem to display it! Any help would be much appreciated!

6
  • What code are you using when you are using push? OR - could you place an id on each item so you don't need positional indexes? Commented Sep 14, 2017 at 20:16
  • push would alter the original array, does not return it Commented Sep 14, 2017 at 20:19
  • 1
    what you mean by "I can't use the index of the item" Commented Sep 14, 2017 at 20:25
  • I'm not sure how to place an id on the item other than than to base the index on the length of the array! Commented Sep 14, 2017 at 20:28
  • well I want to be able to access the items by their position in the list. Which is what I had the index for, but its not working Commented Sep 14, 2017 at 20:29

2 Answers 2

2

What I suspect here is when an event to add a task is emitted, you are trying to set a state for item and then you are immediately setting the items state as well.

React may batch multiple setState() calls into a single update for performance."

Please refer to the docs. So you shouldn't expect item to have your latest item when you try this.setState({items:this.state.items.concat(this.state.item)});

You can have try the following

const item = [{
  text: event.target.value,
  index: this.state.items.length + 1,
  completed:false
 }]

let items = {this.state}
items = items.push(item)
this.setState({items})

You can also pass a function to the setState method

this.setState(function(prevState, props) {
   //Code goes here
});
Sign up to request clarification or add additional context in comments.

Comments

0

By definition, Arrays are immutable data.

To add new item without mutation (and to be most cleaner) exists package immutability-helper.

Install in the project directory

npm install immutability-helper --save

...import in the class

import update from 'immutability-helper'

...and update array

update(this.state.items, {
  $splice: [[0, 0, item]]
})

This code make a "clone" of total_rating and use the $splice to add the new average at the 0th index.

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.