localstorage браузера продолжает сбрасываться до неопределенного

#javascript #reactjs #react-hooks #local-storage

#javascript #reactjs #реагирующие крючки #локальное хранилище

Вопрос:

Я использую ReactJS, я хочу добавить больше элементов к уже существующему элементу в localstorage, но каждый раз, когда я перезагружаю localstorage, значение localstorage сбрасывается до неопределенного…

    React.useEffect(() => {
      localStorage.setItem("cartItems", JSON.stringify(cartItems));

      if (localStorage.getItem("cartItems") !== null) {
         try {
            let existing = localStorage.getItem("cartItems");
            if (existing !== JSON.stringify(cartItems)) {
               try {
                  let newExist = JSON.parse(existing).push(cartItems);
                  localStorage.setItem("cartItems", newExist);
               } catch (e) {
                  console.log("NOOOO")
               }
            }
         } catch (error) {
            console.log("CARTITMES Localstorage is empty")
         }
      } else {
         console.log("Null Cartitems in localstorea")
      }

   })
  

Комментарии:

1. Ваша первая строка localStorage.setItem("cartItems", JSON.stringify(cartItems)); может всегда устанавливать для нее значение empty ( "null" | "undefined" ) , в зависимости от того, что cartItems хранится.

2. можете ли вы показать, как вы получили переменную cartItems до useEffect во второй строке? или, возможно, выполните a console.log(cartItems) перед вызовом setItem и посмотрите, какое значение является первым

Ответ №1:

Первое, что вы делаете, это устанавливаете товары в корзине в локальное хранилище

Предполагается cartItems , что это массив и состояние;

      React.useEffect(() => {
      // this is not necessary here
      //localStorage.setItem("cartItems", JSON.stringify(cartItems));

      if (localStorage.getItem("cartItems") !== null) {
         try {
            let existing = localStorage.getItem("cartItems");

            //this is not the best way to compare Arrys of objects
            
            if (existing !== JSON.stringify(cartItems)) {
               try {
                  //let newExist = JSON.parse(existing).push(cartItems);
                  let newExist = [...JSON.parse(existing), ...cartItems];
                  localStorage.setItem("cartItems", JSON.stringify(newExist));
               } catch (e) {
                  console.log("NOOOO")
               }
            }
         } catch (error) {
            console.log("CARTITMES Localstorage is empty");
           localStorage.setItem("cartItems", JSON.stringify(cartItems));
         }
      } else {
         console.log("Null Cartitems in localstorea");
         localStorage.setItem("cartItems", JSON.stringify(cartItems));
      }

   },[cartItems])
  

Ответ №2:

Разделите свои вызовы useEffect, как показано ниже:

 //First you need to get data from the previous session which should be stored in localstorage already. 
//We are using the key "cartItems" to identify the values we need
//if cartData exists then do something - (most likely JSON.parse(cartData)) if your goal is to work with the data that is stored

      React.useEffect(() => {
      const cartData = localstorage.getItem("cartItems")

      if (cartData) {
         try {

           //Your Logic Here
            }
         } catch (error) {
            console.log("CARTITMES Localstorage is empty")
         }
      } else {
         console.log("Null Cartitems in localstorea")
      }

   }, []);
   
//Below you're stringifying your object and storing it in local storage

   
      React.useEffect(() => {
      localStorage.setItem("cartItems", JSON.stringify(cartItems));
   });