skip to Main Content

I’m trying to understand redux-toolkit. I need to understand why the Add All Products button isn’t adding all the products to redux store’s state. Although add to cart is working for individual items. I just want to do the same thing but want to pass all products in the argument.

Here is the code:

import { useEffect, useState } from "react";
import React from "react";
import { add } from "./store/cartSlice";
import "./styles.css";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
const Products = () => {
  const dispatch = useDispatch();
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchUsers = async () => {
      const res = await fetch("https://fakestoreapi.com/products");
      const data = await res.json();
      console.log(data);
      setProducts(data);
      // alert(products);
    };
    fetchUsers();
  }, []);

  const handleAdd = (product) => {
    dispatch(add(product));
  };
  const handleAddAll = (products) => {
    dispatch(add(products));
  };
  const items = useSelector((state) => state.cart);
  return (
    <div className="productsWrapper">
      <button onClick={() => handleAddAll(products)}>Add All Products</button>
      <h1>Products List</h1>
      <h3>Cart Size: {items.length}</h3>
      <h3>View Cart: {items.map((item) => item.title)}</h3>
      {products.map((product) => (
        <div className="card" key={product.id}>
          <h4>{product.title}</h4>
          <img src={product.image} alt={product.title} />
          <h4>Price: {product.price}</h4>
          <button onClick={() => handleAdd(product)}>Add to cart</button>
        </div>
      ))}
    </div>
  );
};

export default Products;

And here is the link to codesandbox: https://codesandbox.io/p/sandbox/redux-toolkit-listed-trxyrx?file=%2Fsrc%2FProducts.js%3A37%2C35

2

Answers


  1. The issue with your "Add All Products" button not adding all products to the Redux store’s state is related to the way you are handling the dispatch in the handleAddAll function. Currently, you are passing the entire array of products as an argument to dispatch(add(products)).

    Redux actions typically expect a single payload, not an array. To add all products individually, you should map through the products array and dispatch the add action for each product separately.

    Here’s the modified handleAddAll function:

    const handleAddAll = () => {
      products.forEach((product) => {
        dispatch(add(product));
      });
    };
    Login or Signup to reply.
  2. The issue is that you are pushing an array into an array:

    add(state, action) {
      state.push(action.payload);
    }
    

    So if you do: dispatch(add([product1, product2])) then you will end up with something like this in your state: [[product1, product2]]

    You already have the addAll in your store and that looks right, so use that like:

    addAll(state, action) {
      return [...state, ...action.payload];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search