@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 localstorageconstsavedTodos=localStorage.getItem("todos");// if there are todos storedif(savedTodos){// return the parsed the JSON object back to a javascript objectreturnJSON.parse(savedTodos);// otherwise}else{// return an empty arrayreturn[];}});
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("");
}
};
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":
constsavedAllRas=localStorage.getItem("allRas");if(savedAllRas){alert("data is exist");}
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:
constsavedAllRas=localStorage.getItem("allRas");// if there is nothing saved in localstorageif(!savedAllRas){alert("data is exist");// save data localStorage.setItem("allRas",JSON.stringify(allRas));}
How to check if data is exist in localstorage before save the data?
@fbryo we do that when we set the state and use a function instead of an initial state value. Hope that helps!
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:
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":
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:Hope that helps!
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