DEV Community

Discussion on: How to build a React CRUD todo app (add localstorage)

 
joelynn profile image
Joseph Lynn

Looks like you are checking if the data exists here, keep in mind that this is getting an item from localstorage. We are saying, if there is data in local storage then alert "data exists":

  const savedAllRas = localStorage.getItem("allRas");
  if (savedAllRas) {
    alert("data is exist");
  }
Enter fullscreen mode Exit fullscreen mode

If you want to check if data exists first, before saving to localsotrage - there are a few ways you can do it. Check in the useEffect hook or in your example, possibly:

  const savedAllRas = localStorage.getItem("allRas");
  // if there is nothing saved in localstorage
  if (!savedAllRas) {
    alert("data is exist");
    // save data 
    localStorage.setItem("allRas", JSON.stringify(allRas));
  }
Enter fullscreen mode Exit fullscreen mode

Hope that helps!

Thread Thread
 
fbryo profile image
Febry Aryo Riandhito

Sorry, my bad. I revised my problem. The actual problem is, if selected cat/index equals to existed data, shows an alert. And else, it can be saved