Home > Enterprise >  when page reloads items from my cart are not saved
when page reloads items from my cart are not saved

Time:07-07

I'm working on a simple shopping website with React.

I have a problem that every time I add an item to the cart and then go to a different section of the website the page reloads and I lose all the data saved in the cart.

I am not sure if the problem is because of the page reload?

Which is the best approach to try solve this? I'm using react routing.

// indes.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import RouteSwitch from "./components/RouteSwitch";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <RouteSwitch />
  </React.StrictMode>
);

-------------------------------------------------------------------------------------------------

// RouteSwitch.js

import { BrowserRouter, Routes, Route } from "react-router-dom";
import App from "./App";
import Shop from "./Shop";
import About from "./About";
import { useEffect, useState } from "react";
import Cart from "./Cart";

const url = "https://fakestoreapi.com/products";

const RouteSwitch = () => {
  const [products, setProducts] = useState([]);
  const [cart, setCart] = useState([]);

  const getProducts = async () => {
    try {
      const response = await fetch(url);
      const productsList = await response.json();
      setProducts(productsList);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getProducts();
  }, []);

  console.log(cart);

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} />
        <Route
          path="/shop"
          element={<Shop products={products} setCart={setCart} />}
        />
        <Route path="/about" element={<About />} />
        <Route path="/cart" element={<Cart cart={cart} />} />
      </Routes>
    </BrowserRouter>
  );
};

export default RouteSwitch;

-------------------------------------------------------------------------------------------------

// Shop.js (page with all the products)

import React from "react";
import Footer from "./Footer";
import Header from "./Header";

export default function Shop(props) {
  const products = props.products;
  const setCart = props.setCart;

  const addToCart = (product) => {
    setCart((current) => [...current, product]);
  };

  return (
    <>
      <Header />
      <div className="shop__product-list">
        {products.map((product) => {
          return (
            <div className="product-container" key={product.id}>
              <div className="product-desc-top">
                <img
                  className="product-img"
                  alt={product.title}
                  src={product.image}
                />
              </div>
              <div className="product-desc-bottom">
                <p>{product.title}</p>
                <p>${product.price}</p>
                <button
                  className="product-add-to-cart"
                  onClick={() => addToCart(product)}
                >
                  ADD TO CART
                </button>
              </div>
            </div>
          );
        })}
      </div>
      <Footer />
    </>
  );
}

CodePudding user response:

You have to use LocalStorage to save your state.

const getLocalStorage = () => {
  const userData = localStorage.getItem('cartdata')
  if (cartData) {
    return JSON.parse(cartData)
  } else {
    return []
  }
}

const [cart, setCart] = useState(getLocalStorage())

----
 const addToCart = (product) => {

    setCart((current) => {
      localStorage.setItem('cartdata',SON.stringify([...current,product]))
      return [...current, product]
    );
  };

CodePudding user response:

You are saving the products in the state which is memory cache. Every time you reload the page javascript will garbage collect all the data (wipe it out), so you loose it.
The best way to solve it is to store products added to the cart to the database, which requires backend logic and the database.
If this is not real production site you can store the data to local storage and sync it with your state.

CodePudding user response:

I advise you to use localStorage or Cookies.

const [cart, setCart] = useState([]);

React.useEffect(() => {
    localStorage.setItem('cart', JSON.stringify(cart)) // create
}, [cart])

then on the page where you want to get the items

JSON.parse(localStorage.cart) // data
  • Related