ReactJS how to maintain State value when refreshing page

Viewed 8017

I'm trying not to lose my state value which is cart when the page is reloaded. I can add any productto my cartat any page but whenever i reload the page cartstate resets itself. Is there anyway to prevent that with or without using more libraries ? I don't know if Reduxis the only way to prevent this.

My Appfunction:

function App() {
  const [cart, setCart] = useState([]);

  return (
    <div>
      <Router>
        <NavbarComponent cart = {cart} setCart={setCart}></NavbarComponent>
        <Switch>
          <Route exact path="/">
            <Home cart = {cart} setCart={setCart} />
          </Route>
          <Route exact path="/home">
            <Home cart = {cart} setCart={setCart} />
          </Route>
          <Route exact path="/Products">
            <Products cart = {cart} setCart={setCart} />
          </Route>

          <Route exact path="/Detail/:product_id">
            <Detail cart = {cart} setCart={setCart} ></Detail>
            </Route>
        </Switch>
      </Router>
    </div>
  );
}

And this below is just one of my components I can change my cart state value.

export function CardComponent(props) {
  const { cart, products, setCart } = props;
  //const products = props.products;

  const addToCart = (product) => {
    
    let tempCart = [...cart]
    tempCart.push(product); 
    setCart(tempCart)
    console.log(cart);
  };

  return (
    <div className="container cards">
      <div className="featured">
        Featured Products
        {cart.length}
        <div className="featured-underline"></div>
      </div>
      <CardColumns>
        {products.map((product, index) => {
          if (product.is_featured)
            return (
              <Card key={index}>
                <CardImg
                  top
                  width="100%"
                  src="https://dl.airtable.com/.attachmentThumbnails/5ebc46a9e31a09cbc6078190ab035abc/8480b064"
                  alt="Card image cap"
                />
                <CardBody>
                  <CardTitle tag="h5">{product.name}</CardTitle>
                  <CardSubtitle tag="h6" className="mb-2 text-muted">
                    Card subtitle
                  </CardSubtitle>
                  <CardText>{product.description}</CardText>
                  <Button onClick={() => addToCart(product)} color="primary">
                    Add to cart
                  </Button>
                  <Button color="info ml-2">Detail</Button>
                  <p style={{ float: "right", color: "brown" }}>
                    ${product.price}
                  </p>
                </CardBody>
              </Card>
            );
          else return;
        })}
      </CardColumns>
    </div>
  );
}
2 Answers

Please use Redux-Persist if you're using Redux or else just load the data from localStorage when the component mounts and save it to localStorage when the component dismounts

Related