0

This is the current state

state={
    product:[
        {id:1, title: 'demo product 1 ', price: 10, incart: 2},
        {id:2, title: 'demo product 2', price: 11, incart: 3},
    
    
    ],
}

I have a +1 button that increase the total number of product in incart.

// the onClick handler 
// prod arguments return a product object like this {id:1, title: 'demo product 1 ', price: 10, incart: 2}

handelIncrement= (prod) => {
    
    const newState = {...this.state.product, prod}  
    this.setState({ product: newState })  // giving an error
    
  }

I appreciate your help 🙏

3 Answers 3

2

what you are doing is you pass an object to a product state and a product state is an array.

handelIncrement= (prod) => {
    
    const newState = [...this.state.product, prod]  
    this.setState({ product: newState })  // giving an error
    
  }

Sign up to request clarification or add additional context in comments.

4 Comments

I see, how can I overwrite the child object of the array? my approach [...this.state.product, prod] adding a new object into the array. but I want to overwrite the previous object that has the same id as prod.id
Then the best approach is using then index to update the data
Would you please show me the code? I am not an expert.
Sure I will upload the code and you need to pass the current object index to the method.
0
handleIncrement= (prod) => {
    
    this.setState({
      data: this.state.product.map(el => (el.id === id ? {...el, text} : el))
    });
    
  }

Comments

0

To handleincrement() method you need to pass index to method to that.

handelIncrement= (index,prod) => {
    //first copy data
    const copyProducts = [...product];
    //copy current object data
    const singleObjectData = { ...copyProducts[index] };
    //change object data
    singleObjectData = {//your new current prod};
    //put back to the same index
    copyProducts[index] = singleObjectData;
    //and update set
     this.setState({ product: copyProducts })
  }

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.