Then I have to count how many times a user enters a react js web page. I tried to use localStorage but I don’t get the logic to use it as I can do it.
For now I tried to look on the internet for localStorage logic that could give me a hand in writing the code.
const totView = () => {
let view = localStorage.getItem('countView');
if (!view) {
localStorage.setItem('countView', 1);
view = 1;
} else {
view = parseInt(view) + 1;
localStorage.setItem('countView', view);
}
}
3
Answers
You need to add a
useEffect
hook that runs only once when the component mounts.Inside the hook, check if the
localStorage
has a key for the page count.If it doesn’t, set the count to 1. If it does, increment the count by 1.
You can use
useEffect
hook to solve this problemI add code below.
You can do this with the help of useState, useEffect and LocalStorage.
First, we fetch the local storage with the key "pageViews" If it’s present we parse the value as int (because we are storing it as string) and setting it to the state.
Then, we are updating it with +1 and storing it as a string.
Here is the stackblitz demo