DEV Community

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

Collapse
 
fbryo profile image
Febry Aryo Riandhito

How to check if data is exist in localstorage before save the data?

Collapse
 
joelynn profile image
Joseph Lynn • Edited

@fbryo we do that when we set the state and use a function instead of an initial state value. Hope that helps!

const [todos, setTodos] = useState(() => {
    // get the todos from localstorage
    const savedTodos = localStorage.getItem("todos");
    // if there are todos stored
    if (savedTodos) {
      // return the parsed the JSON object back to a javascript object
      return JSON.parse(savedTodos);
      // otherwise
    } else {
      // return an empty array
      return [];
    }
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fbryo profile image
Febry Aryo Riandhito • Edited

But I still save the data, the purpose is I want to check if data is exist before save the data

Here's my modified code:

const handleFormSubmit = (e) => {
e.preventDefault();

// check if value exist
const savedAllRas = localStorage.getItem("allRas");
if (savedAllRas) {
  alert("data is exist");
} else {
  // don't submit if the input is an empty string
  if (deskripsi !== "") {
    setCurrentCat(currentTutorial.id);
    // set the new todos state (the array)
    setAllRas([
      // copy the current values in state
      ...allRas,
      {
        // set a text property to the value of the todo state and
        // trim the whitespace from the input
        id: currentTutorial.id,
        image: currentTutorial.url,
        ras: ras,
        deskripsi: deskripsi,
      },
    ]);

    alert("data successfully added");
  } else {
    alert("data cannot be empty");
  }

  // clear out the input box
  setDeskripsi("");
}
};
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
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