Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Updating state when state is an array of objects. React

I'm working on a shopping cart in react by using context. My problem is with changing the state that has an array of objects.

My array will look like this [{itemId: 'ps-5', qty:4}, {itemId: 'iphone-xr', qty:2}]

Here is my code check the comment

export const CartContext = createContext()

class CartContextProvider extends Component {

    state = {
        productsToPurchase: []
    }

    addProduct = (itemId)=> {
        if (JSON.stringify(this.state.productsToPurchase).includes(itemId)){
            // Add one to the qty of the product
            this.state.productsToPurchase.map(product=>{
                if (product.itemId === itemId){
                    // This is wrong I have to use setState(), but the syntax is a little bit complex
                    product.qty = product.qty + 1
                }
            })
        }
        else {
            this.state.productsToPurchase.push({itemId: itemId, qty: 1})
        }
    }

    render() {
        return (
            <CartContext.Provider value={{...this.state, addProduct: this.addProduct}}>
                {this.props.children}
            </CartContext.Provider>
        )
    }
}

export default CartContextProvider;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are updating the state directly, but you have to use this.setState to update it,

Live Demo

Codesandbox Demo

addProduct = (itemId) => {
  this.setState((oldState) => {
    const objWithIdExist = oldState.productsToPurchase.find((o) => o.itemId === itemId);
    return {
      productsToPurchase: !objWithIdExist
        ? [...oldState.productsToPurchase, { itemId, qty: 1 }]
        : oldState.productsToPurchase.map((o) =>
            o.itemId !== itemId ? o : { ...o, qty: o.qty + 1 }
          )
    };
  });
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!