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
use this code :
You need the following changes to achieve what you are looking for:
useEffect
callbackThis will call the
onPageUnload
function when the component is unloaded. This is the clean up function that is automatically called byuseEffect
– docs here.<StrictMode></StrictMode>
from your index.js. Wrapping your code withStrictMode
calls it twice on dev server. It will be called only once on production. More details in this SO answer.