skip to Main Content

i am not able to fix bug

const products = useSelector((state) => state.cart)

i am getting the undefind value in console

import { useSelector } from 'react-redux'

const Cart = () => {
  const products = useSelector((state) => state.cart)
  console.log('products : ' + products);
  return (
    <>
      <div className='container'>
        {
          products.map((e) =>
            <div className='col-sm-6 col-md-6 col-lg-4 col-xl-3 py-1' key={e.id}>
              <div className="card" style={{ width: "18rem", margin: "auto", height: '25rem' }} >
                <img src={e.image} className="card-img-top" alt="..." style={{ width: "16rem", height: "14rem" }} />
                <div className="card-body">
                  <p className="card-title">{e.title}</p>
                  <h5 className="card-text">${e.price}</h5>
                  <button className="btn btn-primary">Add to Cart</button>
                </div>
              </div>
            </div>
          )
        }
      </div>
    </>
  )
}

export default Cart

this is my cartSlice part

import { createSlice } from '@reduxjs/toolkit'

const cartSlice = createSlice({
    name: 'cart',
    initialState: [],
    reducers: {
        add(state, action){
            state.push(action.payload)
        },
        remove(state, action){
            return state.filter(item => item.id !== action.payload)
        }
    }
})

export const {add, remove} = cartSlice.actions;
export default cartSlice.reducer;

please help me out

in this below code we are getting the value but data is coming undefined

import { useSelector } from 'react-redux'
import { Link } from 'react-router-dom'

const Navbar = () => {

    const item = useSelector((state)=> state.cart)
    console.log(item);
    const navStyle = { cursor: 'pointer'}
    return (
        <>
            <nav className="navbar navbar-expand-lg navbar-light bg-light">
                <div className="container-fluid">
                    <Link className="navbar-brand" to={'/'}>Navbar</Link>
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>
                    <div className="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul className="navbar-nav m-auto mb-2 mb-lg-0">
                            <li className="nav-item">
                                <Link className="nav-link active" aria-current="page" to={'/'}>Home</Link>
                            </li>
                            <li className="nav-item">
                                <Link className="nav-link" to={'/cart'}>cart</Link>
                            </li>
                            <li className="nav-item">
                                <span className="nav-link" style={navStyle} to={'/'}>Count item : {item.length}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </>
    )
}

export default Navbar

2

Answers


  1. well there could be only 1 reason its giving the undefined (reading ‘image’) error its because :-

    products array does not contain any field name "image", thats why when u are trying to use (e.image) is giving u the undefined error and when u are using other fields like id , price and title its not giving error becaue they are present in the products array

    Login or Signup to reply.
  2. import { configureStore, createSlice } from '@reduxjs/toolkit';
        
        const cartSlice = createSlice({
          name: 'cart',
          initialState: {
            products: [] // Initial state with an empty products array
          },
          reducers: {
            addToCart: (state, action) => {
              state.products.push(action.payload);
            }
            // Other reducers can be added here if needed
          }
        });
        
        export const { addToCart } = cartSlice.actions;
        
        const store = configureStore({
          reducer: {
            cart: cartSlice.reducer
          }
        });
        
        export default store;
        
        
        import React from 'react';
        import { useSelector, useDispatch } from 'react-redux';
        import { addToCart } from './store'; // Update the path accordingly
        
        const Cart = () => {
          const products = useSelector(state => state.cart.products);
          const dispatch = useDispatch();
        
          return (
            <div>
              <h2>Cart</h2>
              {products.map(product => (
                <div key={product.id}>
                  <img src={product.image} alt={product.title} />
                  <h3>{product.title}</h3>
                  <p>${product.price}</p>
                  <button onClick={() => dispatch(addToCart(product))}>Add to Cart</button>
                </div>
              ))}
            </div>
          );
        };
        
        export default Cart;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search