EdG
EdG

Reputation: 2351

push method not returning new array

I am adding an object to an array through javascript push() method. My array is an array of objects. I want to console.log() the new array. But it is giving me the length of new array. I know push() method returns the length of new array but I want to use the new array in my application. How to get it

    let sub_sprite = this.state.sub_sprite;
    let updated_sub_subsprite;
    updated_sub_subsprite = sub_sprite.push(this.state.sprite[that.state.sprite_count]);
    console.log(updated_sub_subsprite);

    that.setState({sub_sprite:updated_sub_subsprite}, ()=>{
         console.log(this.state.sub_sprite)
    });

Upvotes: 1

Views: 79

Answers (2)

Patrick Hund
Patrick Hund

Reputation: 20256

Do not use Array.push on an array stored in your React component's state, it will mutate the state directly, which may lead to problems (see this article).

You can use Array.concat to create a new array with the additional value:

let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = sub_sprite.concat([this.state.sprite[that.state.sprite_count]]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

A more consise and convenient way is using the spread syntax (notice the three dots):

let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = [...sub_sprite, this.state.sprite[that.state.sprite_count]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30390

The Array#push method does not return a new array, but rather the length of the array after the item(s) have been added to that array instance.

It looks like the Array#concat method would be a better fit for what you're trying to do, seeing that offers the "appending behavior" and also returns the resulting array.

Consider making the following adjustments to your code, making use of concat() to achieve what you want:

let sub_sprite = this.state.sub_sprite;

// Create a new array via concat(), adding a new array with one item 
// that is [ sub_sprite [that.state.sprite_count] ] to sub_sprite
let updated_sub_subsprite = sub_sprite.concat( [ sub_sprite [that.state.sprite_count] ]);

console.log(updated_sub_subsprite);

that.setState({sub_sprite : updated_sub_subsprite }, ()=>{
    console.log(this.state.sub_sprite)
})

Upvotes: 0

Related Questions