Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an item to the front of a state array in React

Tags:

reactjs

I know that you can add items to the end of the array with concat but how do I unshift to add an item to the front?

Add to the end:

var allStatuses = this.state.statusData;
var newStatuses = allStatuses.concat([data.statuses]);
this.setState({statusData: newStatuses});

What I want to do is change the "concat" to something that will put data.statuses to the front and not the end.

like image 865
Rubicksman Avatar asked Jan 20 '16 15:01

Rubicksman


3 Answers

Is there a problem doing

[data.statuses].concat(allStatuses);

If you are using ES6, you can do

var newStatuses = [data.statuses, ...allStatuses]
like image 168
Abhishek Jain Avatar answered Nov 18 '22 19:11

Abhishek Jain


Actually you can use .concat in this case,

var newStatuses = [data.statuses].concat(allStatuses);
like image 44
Oleksandr T. Avatar answered Nov 18 '22 17:11

Oleksandr T.


If you want to modify the original array, use Array.unshift

var arr = [1,2,3];
arr.unshift(0);
arr // 0,1,2,3

If you want a new array, use Array.concat as Alexander suggested

this.setState({statusData: [0].concat(this.state.statusData)})

Which is similar to spreading into a new array

this.setState({statusData: [0, ...this.state.statusData]})
like image 44
Juan Mendes Avatar answered Nov 18 '22 17:11

Juan Mendes