Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS how to maintain State value when refreshing page

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>
  );
}
like image 287
Ali Ziya ÇEVİK Avatar asked Dec 10 '20 09:12

Ali Ziya ÇEVİK


People also ask

Does Redux state reset on refresh?

When we refresh page in a web-app, the state always resets back to the initial values which in not a good thing when you try to build some large web-app like e-commerce. We can manually do the state persistent using the native JavaScript localStorage.

How do you persist state in React native?

To be able to persist the navigation state, we can use the onStateChange and initialState props of the container. onStateChange - This prop notifies us of any state changes. We can persist the state in this callback. initialState - This prop allows us to pass an initial state to use for navigation state.


2 Answers

The data has to somehow persist - meaning you have to actually save it somewhere.

You could use the localStorage on the client. Then just make sure to update it whenever cart changes.

something like:

  const [cart, setCart] = useState(localStorage.getItem('cart'));

  useEffect(()=>{
      localStorage.setItem('cart', cart)
  },[cart]);
docs:
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
  • https://reactjs.org/docs/hooks-effect.html
like image 161
aviya.developer Avatar answered Oct 18 '22 02:10

aviya.developer


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

like image 29
Ayudh Avatar answered Oct 18 '22 01:10

Ayudh