skip to Main Content

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


  1. 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.

    import { useEffect } from 'react';
    
    function MyComponent() {
      useEffect(() => {
        const count = localStorage.getItem('pageCount');
        if (!count) {
          localStorage.setItem('pageCount', 1);
        } else {
          localStorage.setItem('pageCount', parseInt(count) + 1);
        }
      }, []);
    
      return (
        // your component code here
      );
    }
    Login or Signup to reply.
  2. You can use useEffect hook to solve this problem

    I add code below.

    useEffect(() => {
      localStorage.setItem(
        "pageCount",
        parseInt(localStorage.getItem("pageCount") || 0) + 1
      );
    }, []);
    
    Login or Signup to reply.
  3. You can do this with the help of useState, useEffect and LocalStorage.

    import React, { useState, useEffect } from 'react';
    
    const App = () => {
      const [pageViews, setPageViews] = useState(0);
    
      useEffect(() => {
        const storedPageViews = localStorage.getItem('pageViews');
    
        if (storedPageViews) {
          setPageViews(parseInt(storedPageViews, 10));
        }
    
        setPageViews((prevPageViews) => {
          const newPageViews = prevPageViews + 1;
          localStorage.setItem('pageViews', newPageViews.toString());
          return newPageViews;
        });
      }, []);
    
      return (
        <div>
          <h1>Page View Counter</h1>
          <p>This page has been viewed {pageViews} times.</p>
        </div>
      );
    };
    
    export default App;
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search