in React, I want to keep state after refreshing page

Viewed 49

In React, I want to keep state after refreshing page. I tried to use localStorage but every time I refresh page it keeps clearing data.

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

  const items = [
    {
      name: "xx99 mark || headphones",
      description: "This huge e-commerce challenge will provide an incredible test for your front-end skills. Once you're done, you'll have an amazing project to add to your portfolio!",
      img: "https://images.pexels.com/photos/205926/pexels-photo-205926.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
      price: 159
    },
    {
      name: "xx99 mark | headphones",
      description: "This huge e-commerce challenge will provide an incredible test for your front-end skills. Once you're done, you'll have an amazing project to add to your portfolio!",
      img: "https://images.pexels.com/photos/610945/pexels-photo-610945.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
      price: 120,
    },
    {
      name: "x99 mark || headphones",
      description: "This huge e-commerce challenge will provide an incredible test for your front-end skills. Once you're done, you'll have an amazing project to add to your portfolio!",
      img: "https://images.pexels.com/photos/3945667/pexels-photo-3945667.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
      price: 400
    },
  ]

  localStorage.setItem("cart-item", JSON.stringify(cart))
  
  return (
    <>
      <userContext.Provider value={{ selected, setSelected, items, cart, setCart }}>

        <BrowserRouter>
          <Navbar />
          <Routes>
            <Route path='/' element={<Home />} />
            <Route path='/headphones' element={<Headphones />} />
            <Route path='/speakrs' element={<Speakers />} />
            <Route path='/earphones' element={<Earphones />} />
            <Route path='/cart' element={<Cart />} />
          </Routes>
        </BrowserRouter>
      </userContext.Provider>
    </>

  );
}


2 Answers

Can you check if the items are saved in the local storage in the first place?

Run your app -> go to console -> application -> local storage

Can you see any data there?

Changing

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

to

const [cart, setCart] = useState(localStorage.getItem("cart-item") ?  JSON.parse(localStorage.getItem("cart-item")) : [])

should work fine.

Related