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 />
</>
);
}