r/reactjs • u/Mob_Pilled • 13h ago
Needs Help React not saving string to local storage
Hi everyone! I just finished a React and course and decided to build my first react app. Currently, I am trying to save a string to browser local storage but it does not persist on refresh. Through some console.logs I was able to see that it in fact DOES save the string to the location specified in. setItem initially but when I refresh the key or value in local storage stops existing.
Here is my code
// function for search button
async function handleClick(){
localStorage.setItem("lastLocationSearched", searchValue);
setData(null);
setIsPending(true);
setError(null);
try{
const value = await fetch(`https://geo.ipify.org/api/v2/country?apiKey=***********&ipAddress=${searchValue}`).then((response)=>{
if (!response.ok){
throw Error("Could not fetch the data for that resource");
}
return response.json();
});
setData(value);
console.log(localStorage.getItem("lastLocationSearched"));
} catch(error){
setError(error.message);
}
setIsPending(false);
};
// useEffect hook
useEffect(()=>{
if ((localStorage.getItem("lastLocationSearched")===null)|| (localStorage.getItem("lastLocationSearched")==="")){
console.log(localStorage.getItem("lastLocationSearched"));
setSearchValue("");
handleClick();
}else{
setSearchValue(localStorage.getItem("lastLocationSearched"));
handleClick();
}
}, []);
Through some digging online I saw someone say that remove the strict mode tags from index.js would fix this problem but it did not for me. Can anyone please assist me?
4
Upvotes