简体   繁体   中英

How can I persist localstorage when ComponentDidMount resets the value on refresh?

I am appending an item to each array item when fetching from a list and setting it to zero. Then running the function in ComponentDidMount().

newsList = (category) => {
    fetch(API_URL)
      .then((response) => response.json())
      .then((response) => {
        var news = response.articles;
        news = news.map((x) => ({ ...x, likes: 0 }));
    
          this.setState({ general: news }, () => {
            localStorage.setItem("general", JSON.stringify(this.state.general));
          });
      });
  };

I am subsequently incrementing the 'like' value I appended and saving to local storage.

generalLikeCount = (x) => {
    let newArr = [...this.state.general];
    newArr[x]["likes"] = parseInt(newArr[x]["likes"]) + 1;
    this.setState({ general: newArr }, () => {
      localStorage.setItem("general", JSON.stringify(this.state.general));
    });
  };

But on every refresh, likes counter is reset to zero. I'm not sure how to fix this.

In case anyone has the same issue, I fixed this by checking if the value exists in local storage and using that value instead, or initializing it if it doesn't exist.

Like so:

if(JSON.parse(localStorage.getItem(category)) !== null || undefined ) {
          news = JSON.parse(localStorage.getItem(category));
        } else {
          news = news.map((x) => ({ ...x, likes: 0 }));
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM