Nespony
Nespony

Reputation: 1371

Add to an array in React

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!

Upvotes: 0

Views: 5546

Answers (2)

Rafael Pizao
Rafael Pizao

Reputation: 841

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.

Upvotes: 0

Brr Switch
Brr Switch

Reputation: 984

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
});

Upvotes: 2

Related Questions