carloscc
carloscc

Reputation: 799

setState won't update React Native

I have a React Native application with the following function:

delete(index){
        this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: this.state.Cart.splice(index,1) },
            function(){
                console.log(this.state.cachedCart);
                Toast.show({
                text: 'Item deleted from Cart',
                position: 'bottom',
                buttonText: 'Undo',
                duration: 2000,
                onClose: this.undoDelete.bind(this)
            });
        });

    }

My problem is that deletedIndex and cachedCart won't update if I am also updating the state of Cart. However, If I remove Cart: this.state.Cart.splice(index,1) everything works fine. I have tried with hardcoded values for deletedIndex and cachedCart and wouldn't work either. I am always doing the console.log inside the function that should run after setState.

Upvotes: 2

Views: 147

Answers (2)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

The issue with your code was that this.state.Cart.splice(index,1) was returning the deleted item and that value you were setting as a state.

  delete(index){
    console.log("state", this.state);
    // Cloning the this.state.cart to updatedCart
    let updatedCart = this.state.cart.slice();
    // Removing the index element
    updatedCart.splice(index,1);
    
    this.setState({deletedIndex:index, cachedCart:this.state.cart, cart: updatedCart },
        ()=>{
          console.log("state", this.state);
    });

}

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30390

You should be able to resolve this by taking a clone/copy of the cart, rather than mutating the same cart instance that you are caching. One approach to this might be:

delete(index){

    // Use filter to clone the Cart array instance, while excluding 
    // the cart item that you want to delete (ie at index)
    const newCart = this.state.Cart.filter(function(item, i) { return i !== index });

    this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: newCart },
        function(){
            console.log(this.state.cachedCart);
            Toast.show({
            text: 'Item deleted from Cart',
            position: 'bottom',
            buttonText: 'Undo',
            duration: 2000,
            onClose: this.undoDelete.bind(this)
        });
    });

}

Upvotes: 2

Related Questions