Denis Koval
Denis Koval

Reputation: 11

How to remove an element from an array dynamically? React.js

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;

Upvotes: 1

Views: 915

Answers (1)

windowsill
windowsill

Reputation: 3649

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)
    )
  }

...

Upvotes: 1

Related Questions