1

There are two components, I want to implement an element array using the useContext hook, but when the button is clicked, the element is not removed, but on the contrary, there are more of them. Tell me what is wrong here. I would be very grateful!

First component:

import React from 'react';
import CartItem from './CartItem';
import Context from '../Context'; 

function Cart() {
    let sum = 0;
    let arrPrice = [];
    let [products, setProducts] = React.useState([]);
    let loacalProsucts = JSON.parse(localStorage.getItem('products'));

    if(loacalProsucts === null) {
        return(
            <div className="EmptyCart">
                <h1>Cart is empty</h1>
            </div>
        )
    } else {
        {loacalProsucts.map(item => products.push(item))}
        {loacalProsucts.map(item => arrPrice.push(JSON.parse(item.total)))}
    }

    for(let i in arrPrice) {
        sum += arrPrice[i];
    }

    function removeItem(id) {
        setProducts(
            products.filter(item => item.id !== id)
        )
    }

    return(
        <Context.Provider value={{removeItem}}>
            <div className="Cart">
                <h1>Your purchases:</h1>
                <CartItem products = {products} />
                <h1>Total: {sum}$</h1>
            </div>
        </Context.Provider>
    )
}

Second component:

import React, { useContext } from 'react';
import Context from '../Context';

function CartList({products}) {
    const {removeItem} = useContext(Context);
    return(
        <div className="CartList">
            <img src={products.image} />
            <h2>{products.name}</h2>
            <h3 className="CartInfo">{products.kg}kg.</h3>
            <h2 className="CartInfo">{products.total}$</h2>
            <button className="CartInfo" onClick={() => removeItem(products.id)}>&times;</button>
        </div>
    );
}

export default CartList;

Component with a context:

import React from 'react';

const Context = React.createContext();

export default Context;
1
  • All the code that is in your render loop, like products.push(item) will run every time the component renders. That's what React hooks are for. Commented Nov 11, 2020 at 22:46

1 Answer 1

1

Adding to the comment above ^^

It's almost always a mistake to have initialization expressions inside your render loop (ie, outside of hooks). You'll also want to avoid mutating your local state, that's why useState returns a setter.

Totally untested:

function Cart() {
  let [sum, setSum] = React.useState();
  const loacalProsucts = useMemo(() => JSON.parse(localStorage.getItem('products')));
  // Init products with local products if they exist
  let [products, setProducts] = React.useState(loacalProsucts || []);

  useEffect(() => {
    // This is actually derived state so the whole thing
    // could be replaced with
    // const sum = products.reduce((a, c) => a + c?.total, 0);
    setSum(products.reduce((a, c) => a + c?.total, 0));
  }, [products]);

  function removeItem(id) {
    setProducts(
      products.filter(item => item.id !== id)
    )
  }

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

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.