I'm playing around with local storage can't seem to get this to work this is very simple just to play around with it but the code.
const [isFavorite, setIsFavorite] = useState(false);
const favorite = () => {
setIsFavorite(!isFavorite) ? localStorage.setItem('name', search[0].title) : localStorage.clear()
}
return(
<button onClick={favorite} className="favorite">Favorite: {isFavorite ? <FaHeart /> : <FaRegHeart />} </button>
)
Why is is that on the initial click the value is stored but when clicked again localStorage.clear() is not being run, can it not be used in a ternary operator or am I just using it wrong?
Also I have tried switching the order in the ternary but it doesn't seem the .clear() ever gets called.
CodePudding user response:
First of all, get the new value separately. You should not count on a set hook value. Secondly, the ternarnik for the call functions is not pure code - use if else. Good luck in studying React.
const favorite = () => {
const newFavoriteState = !isFavorite;
setIsFavorite(newFavoriteState)
if (newFavoriteState)
localStorage.setItem('name', search[0].title)
else
localStorage.clear()
}
CodePudding user response:
setIsFavorite(!isFavorite) ? localStorage.setItem('name', search[0].title) : localStorage.clear()
This code is more or less equivalent to:
const x = setIsFavorite(!isFavorite)
if (x) localStorage.setItem('name', search[0].title)
else localStorage.clear()
What does the the setIsFavorite(!isFavorite)
return? Probably not the value you expect.
Try using it separately
setIsFavorite(!isFavorite);
!isFavorite ? localStorage.setItem('name', search[0].title) : localStorage.clear();