Home > Net >  UseEffect does not rerender when remove data out of an array only upon adding data does it rerender
UseEffect does not rerender when remove data out of an array only upon adding data does it rerender

Time:01-07

import React, { useEffect, useState } from 'react'
import { HiOutlineBackspace } from "react-icons/hi";
import {MdOutlineCancel} from 'react-icons/md'

const Cart = ({toggleCart}) => {
  const localStorageCart = JSON.parse(localStorage.getItem('MY_CART')) || []
  const [cartItem, setCartItem] = useState(localStorageCart)
*************************************  
  const handleDeleteButton = (index) => {
    cartItem.filter(cartItem[index])
    console.log(cartItem);
  }
**************************************
  useEffect(() =>{
    setCartItem(cartItem)
  },[cartItem])

  return (
    <div className='cartContainer'>
      <h1 style={{textAlign:"center"}}>Your Cart</h1>     
      <button 
      style={{backgroundColor:'transparent'}}
      onClick={toggleCart}
      >
        <HiOutlineBackspace/>
      </button>

      <div className='cartCardContainer'>  
      {cartItem.map((cartItem,index) =>{
        return(
          <div className="cartCard" key={index}>
            <img src={cartItem.img} alt="logo" id="img" />
            <h2>{cartItem.title}</h2>

            <div className="description">
              <h5>{cartItem.description}</h5>
            </div>

            <div className="priceCard"  >
              <h3>${cartItem.price}</h3>
            </div>
            <button onClick={() => handleDeleteButton(index)}>***********************
              <MdOutlineCancel/>
            </button>
        </div>
        )
      })}
        
      </div>
    </div>
  )
}

export default Cart

I am working on an e-commerce add to Cart function.

By using useEffect I managed to rerender the cart right upon adding an item since it was a one-page app.

But when I tried to splice( ) the cartItem I heard that it is not a good practice and that I should use filter( ) instead but I am having trouble doing so as I have tried many ways and the filter doesn't go as planned or it just dont run.

For this part of the project I use a lot of Local Storage as it is the addToCart component

I have put * symbol on where I think the problem might be

CodePudding user response:

The filter method returns a new array based on the condition you provide it. So in your code you're not actually altering the state of your cartItem.

Filter your cartItem array and use the return value to set your cartItem state.

const handleDeleteButton = (index) => {
    setCartItem(cartItem.filter(...));
}

As a side note, you would be better filtering your items by a key or identifier associated with the item rather than the index value of your map function.

CodePudding user response:

The filtering is not implemented correctly. Also, you have to update the state after filtering/removing items from the state.

You can use splice() to remove an element from an array.

The following is how handleDeleteButton should look like:

const handleDeleteButton = (index) => {
  cartItem.splice(index, 1)); // 1 means remove one item only
  setCartItem([...cartItem]);
}

CodePudding user response:

useEffect woke when you are updating the state your state now is cartItem, To update this state most be execute setCartItem well in your function well you must do this :

setCartItem(cartItem.splice(cartItem[index],1)

I do not know what is inside your array cartItem well do you filter and change it with setCartItem

  • Related