skip to Main Content

I tried updating the redux store of my application using a button but each time the button is clicked and the data from the api is mapped through, it doesn’t update the store with the value as expected.

I logged the expected value (product.title) to the console then I noticed that it disappears almost immediately as it appears on the console.
What do I do to make is stay

Here is my code

import { useEffect, useState } from "react";
import "../styles/BestSellers.css";
import { useDispatch } from "react-redux";
import { setItem } from "../features/ProductState";

function BestSellers() {
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(10);
  const dispatch = useDispatch();

  useEffect(() => {
    fetch(`https://dummyjson.com/products?limit=${count}`)
      .then((res) => res.json())
      .then((data) => {
        setProducts(data.products);
      });
  }, [count]);

  const loadMore = () => {
    setCount((prevCount) => prevCount + 5);
  };

  const handleAction = (product) => {
    dispatch(
      setItem({
        title: product.title,
        image: product.image,
        price: product.price,
      })
    );
  };

  return (
    <div className="container">

      <div className="products">
        {products.map((product) => (
          <a
            onClick={() => {
              handleAction(product);
            }}
            className="link"
            href="/shop"
            key={product.id}
          >
            <div className="product">
              <h5>{product.title}</h5>
              <p>English Department</p>
              <span className="prices">
                <h4 className="discount">$16.48</h4>
                <h4>${product.price}</h4>
              </span>
            </div>
          </a>
        ))}
      </div>

      <button onClick={loadMore} className="btn">
        LOAD MORE PRODUCTS
      </button>
    </div>
  );
}

export default BestSellers;

3

Answers


  1. You are using anchor tags instead of buttons. The anchor tag is reloading the page when clicked, and when the page reloads your Redux store is re-initialized. Don’t use anchor tags like this.

    Example using button element:

    <div className="products">
      {products.map((product) => (
        <button
          key={product.id}
          onClick={() => {
            handleAction(product);
          }}
          className="link"
        >
          <div className="product">
            <h5>{product.title}</h5>
            <p>English Department</p>
            <span className="prices">
              <h4 className="discount">$16.48</h4>
              <h4>${product.price}</h4>
            </span>
          </div>
        </a>
      ))}
    </div>
    
    Login or Signup to reply.
  2. Because you use <a></a> element
    You can try useing <button />

    Login or Signup to reply.
  3. Navigation within a one page application should be done via the router to ensure you dont reload / reinitialize the page. Similar to a reload button in the browser, this would initialize the redux store.

    Depending on your react version the navigation needs to be handled slightly different. Here a few examples from a different post: https://stackoverflow.com/a/42121109/19801189
    For the interaction with the shop buttons with an onClick would probably be best.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search