ReactJS how to maintain State value when refreshing page
Asked Answered
S

5

7

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>
  );
}
Shitty answered 10/12, 2020 at 9:7 Comment(2)
You can use multiple things, for instance Redux, Context, MobX, or you can just store your cart data in local storage, but you have your state backed with something, because on refresh all data are lost.. Easiest way is local storageMilter
Whilst you can use localstorage, I would recommend to use something like this sparingly and only when really needed, and have your components refetch data on refresh were possible. you'll run into a lot less issues, in particular out of date data not being fetched when neededOnomastics
D
3

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:
Dreamworld answered 10/12, 2020 at 9:13 Comment(1)
Did you try with the useEffect?Dreamworld
R
2

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

Rely answered 10/12, 2020 at 9:13 Comment(0)
H
0

When you refresh the page, it will surely start to re-render and the state will be lost. So save it to a local variable and then add it to the card components.

Henigman answered 17/7, 2023 at 7:45 Comment(0)
W
0

you should use in your code localStorage. Because when you refresh the page, your state is empty but local storage stores data.

useEffect(() => {
    let newCartData = localStorage.getItem("Product")
    if (newCartData === []) {
        return []
    }
    else {
        return JSON.parse(newCartData)
    }

}, [])

const addToCart = (product) => {
    localStorage.setItem("Product", JSON.stringify(product))
}
Whity answered 28/8, 2023 at 21:3 Comment(1)
B
0

When you refresh the page you are gonna lose the current state that it is not stored anywhere else so you have to first store it somewhere. To store the state you can either directly store it in the localStorage or you can use the redux-toolkit. In my opinion redux-toolkit is the best option.

You need to install redux-toolkit and then create slices and store according to your use which is very flexible to reuse and empty the states when needed.

Beals answered 20/9, 2023 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.