Reputation: 93
I have like btn, bellow I have span - it will show and count how many times I clicked this like btn. When I reload page, numbers are still there, but if I will try to add more likes it will count from zero. Can you please show me why? Thank you.
function ocko() {
return (
<article className='midleBox'>
<Ocko/>
</article>
)
}
function Ocko () {
return (
<div>
<h3 className='ms-3'>Ocko</h3>
<img src={ockoImg} className='img' style={{width:'100px'}} alt="img"/>
<div className='flexBox'>
<LikesBox/>
<HeartBox/>
<Star/>
</div>
</div>
)
}
const LikesBox = () => {
const [count, setCount] = useState(0)
function clickHandler() {
setCount(count+1)
localStorage.setItem('like', JSON.stringify(count)) // locStorage here
}
return(
<article className='Liker'>
<i class="bi bi-hand-thumbs-up-fill like" onClick={clickHandler}></i>
<span > {localStorage.getItem('like')} </span> // and here
</article>
)
}
Upvotes: 0
Views: 246
Reputation: 5766
Set your initial state based on what is already in local storage
const [count, setCount] = useState(localStorage.getItem('like') || 0);
Also, instead of using local storage to display it, since you're keeping track in your own React state you can just use count
directly
<span > {count} </span>
Upvotes: 1