Home > Blockchain >  React:re-render cart after remove button click
React:re-render cart after remove button click

Time:12-01

I want to re-render cart after remove button click.I think it's working cause , when i click remove then this item is removing from products (I got it from console.log) .But cart is not re-rendering .May be I could not use useEffect hook properly .

import React,{useEffect} from 'react'
import { useSelector } from 'react-redux'
import Link from "next/link"
const cart = () => {
    let products=useSelector((state)=>state)
    const remove=(ID)=>{
      products= products.filter(product=>{
            return product.id!==ID
        })
        console.log(products);
    }
    useEffect(()=>{
    },[products])
  return (
    
    <div className='flex flex-wrap'>
        {
            products && products.map((product)=>{
                return(
                      <div className='bg-gray-700 border-white m-4 rounded-md min-w-[250px]' key={product.id}>
                          <div className='flex flex-col text-white p-4'>
                               <img src={product.image} alt="Image not loaded"/>
                              <h3><b>Product Name:</b> {product.name}</h3>
                              <h3><b>Price:</b> ${product.price}</h3>
                            <button onClick={()=>remove(product.id)} className='bg-gray-800 p-2 my-2 rounded-md hover:bg-black'>REMOVE</button>
                          </div>
                      </div>
                )
              })
        }
        <Link href="/"> <button className='p-2 bg-orange-400 outline-sm  w-20'>HOME</button></Link>
    </div>
  )
}

export default cart

CodePudding user response:

you dont need useEffect to render component instead update the products in reducer using dispatch

import React,{useEffect} from 'react'
import { useSelector ,useDispatch} from 'react-redux'
import Link from "next/link"
const cart = () => {
let products=useSelector((state)=>state)
const dispatch=useDispatch();
    const remove=(ID)=>{
      products= products.filter(product=>{
            return product.id!==ID
        })
        console.log(products);
        dispatch(setProducts(products))
    }

  return (
    
    <div className='flex flex-wrap'>
        {
            products && products.map((product)=>{
                return(
                      <div className='bg-gray-700 border-white m-4 rounded-md min-w-[250px]' key={product.id}>
                          <div className='flex flex-col text-white p-4'>
                               <img src={product.image} alt="Image not loaded"/>
                              <h3><b>Product Name:</b> {product.name}</h3>
                              <h3><b>Price:</b> ${product.price}</h3>
                            <button onClick={()=>remove(product.id)} className='bg-gray-800 p-2 my-2 rounded-md hover:bg-black'>REMOVE</button>
                          </div>
                      </div>
                )
              })
        }
        <Link href="/"> <button className='p-2 bg-orange-400 outline-sm  w-20'>HOME</button></Link>
    </div>
  )
}

export default cart

or you can use this way

    import React,{useState} from 'react'
import { useSelector } from 'react-redux'
import Link from "next/link"
const cart = () => {
    let products=useSelector((state)=>state)
const [data,setData] useState(products);

    const remove=(ID)=>{
      let filterData= products.filter(product=>{
            return product.id!==ID
        })
        console.log(filterData);
setData(filterData)
    }
  return (
    
    <div className='flex flex-wrap'>
        {
            data && data.map((product)=>{
                return(
                      <div className='bg-gray-700 border-white m-4 rounded-md min-w-[250px]' key={product.id}>
                          <div className='flex flex-col text-white p-4'>
                               <img src={product.image} alt="Image not loaded"/>
                              <h3><b>Product Name:</b> {product.name}</h3>
                              <h3><b>Price:</b> ${product.price}</h3>
                            <button onClick={()=>remove(product.id)} className='bg-gray-800 p-2 my-2 rounded-md hover:bg-black'>REMOVE</button>
                          </div>
                      </div>
                )
              })
        }
        <Link href="/"> <button className='p-2 bg-orange-400 outline-sm  w-20'>HOME</button></Link>
    </div>
  )
}

export default cart

CodePudding user response:

i think your useEffect should trigger after the remove function is called! instead of products try putting in remove in the useEffect! Hope this helps!

CodePudding user response:

Whereever you receive the products state from, you should use setProducts() to update the state (if it was created with the useState hook).

products = products.filter(product=>{
            return product.id!==ID
        })

is incorrect. It won't trigger state updates listeners, that's why nothing in the UI changes, as React doesn't know about this change.

You should do something like:

setProducts(products.filter(product=>{
            return product.id!==ID
        }))

Or even better:

setProducts(products => products.filter(product=>{
                return product.id!==ID
            }))

(to use the most up-to-date producst value for the filtering)

Also you should better remove the specific object by its id like:

setProducts(products => products.splice(products.findIndex(p => p.id === ID), 1))
  • Related