skip to Main Content

I want to make a "single" call to one API when particular page is loaded (on Load)
and later when user navigate to some other page then I want to make another call (on un load) using react component. I have created below component for the same but
it hits onload call twice and on unload call single without even unloading the page.

Can some one help to find out the issue.


function ActivityTracker() {
  // Function to make the API call on page load
  const onPageLoad = async () => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/todos/1'
      );
      const data = await response.json();
      // Handle the data as needed
    } catch (error) {
      console.error('Error on page load:', error);
    }
  };

  // Function to make the API call on page unload
  const onPageUnload = async () => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/todos/1'
      );
      const data = await response.json();
      // Handle the data as needed
    } catch (error) {
      console.error('Error on page unload:', error);
    }
  };

  useEffect(() => {
    onPageLoad();
  }, []);

  return <div>Your page content goes here</div>;
}

export default ActivityTracker;

project link on stackblitz -> https://stackblitz.com/edit/stackblitz-starters-b32vmo?file=src%2FActivityTracker.js,src%2FApp.js

2

Answers


  1. use this code :

         function ActivityTracker() {
     // Function to make the API call on page load
       const [res, setRes] = React.useState([]);
    
       // Function to make the API call on page unload
        const onPageUnload = async () => {
        try {
         const response = await fetch(
            'https://jsonplaceholder.typicode.com/todos/1'
          );
          const data = await response.json();
         // Handle the data as needed
        } catch (error) {
         console.error('Error on page unload:', error);
       }
       };
    
    useEffect(() => {
    const onPageLoad = async () => {
      try {
        const response = await fetch(
          'https://jsonplaceholder.typicode.com/todos/1'
        );
        setRes(response.json());
        // Handle the data as needed
      } catch (error) {
        console.error('Error on page load:', error);
      }
    };
      onPageLoad();
     }, [setRes]);
     }
    
    export default ActivityTracker;
    
    Login or Signup to reply.
  2. You need the following changes to achieve what you are looking for:

    1. Return onPageUnload in the useEffect callback
    useEffect(() => {
        onPageLoad();
        return onPageUnload;
    }, []);
    

    This will call the onPageUnload function when the component is unloaded. This is the clean up function that is automatically called by useEffectdocs here.

    1. Remove the <StrictMode></StrictMode> from your index.js. Wrapping your code with StrictMode calls it twice on dev server. It will be called only once on production. More details in this SO answer.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search