When saving data(array of objects) in React.State/ LocalStorage using ReactHooks, facing an error

i am looking to save the customer product selection in basket and to avoid the effect of refesh of page i am also saving the customer selection to local storage, i am use spread ....prevItems and using window.localStorage.setItem ,but as prevItems initial value is null so it comes up with an error of TypeError: prevItems is not iterable , i have tried passing the product,quantity to initial value(to make to iterable afterwards) but the initialvalue= callback is present outside the main function and was unsuccessful. Not sure what else i can do to overcome this issue.
Any suggestions guys.

 let initialvalue = () => {
     return window.localStorage.getItem("user-basket", {});
    };
    
        function App() {
        const [basketItems, setBasketItems] = useState(initialvalue());
    // basketItems will be like[{Product1},{Product2}, and so on...] i.e it will store each product as a new object
     const addBasketitems = (product, quantity) => {
        setBasketItems((prevItems) => {
          console.log("prevItems", prevItems);
          console.log("product", product);// the product customer selected
          console.log("quantity", quantity);// no. of item of a product customer selected
          const newItems = [...prevItems, { ...product, quantity }];
          window.localStorage.setItem("user-basket", JSON.stringify(newItems));
  return newItems;
        });



     <Router>
         
              <Switch>
              
                <Route
                 path="/"
                  exact
                  render={(props) => <Home {...props} userData={userData} userstatus={siginalready} addBasketitems={addBasketitems} 
               />}
             </Switch>
     </Router>
       
    ```

getItem() will return null if nothing is stored in the local storage by that key. Note that it only takes one argument, though. That extra {} you have is ignored.

If you want {} to be a default value, then you need to check for the return of getItem() and if null, return your empty object.

Since you seem to be expecting the item to be an object, you would also need to parse it before returning it, otherwise you’ll return the stringified version of that object. So what you’re looking for with initialvalue() is something more along the lines of:

let initialvalue = () => {
    const value = window.localStorage.getItem("user-basket");
    if (!value) {
        return {};
    }
    return JSON.parse(value);
};
1 Like

i wasnt sure about {} before but makes sense now. Thanks alot :slightly_smiling_face: