Open In App

How to send API call before page reload or close using ReactJS ?

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

To send an API call before the page reloads or closes using React JS we have to link or define a function when the page unloads. The page unloading happens just before the page is closed or tries to reload.

Prerequisites

Approach

We will use some listeners like “beforeupload” and “upload”, which trigger a function that sends API calls. The listener will only trigger the function before the page reloads or closes so that we have the updated result from the API.

Creating React Application

Step 1:Use this command in the terminal to start a react project.

npx create-react-app <folder-name>

Step 2: Move to the project directory

cd <folder-name>

Project Structure

The project structure will look like this.

Example: Example demonstrates sending API call before page reload using beforeunload event listener.

Javascript




import { useState, useEffect } from "react";
 
function App() {
 
    const [data, setData] = useState("Loading...");
 
    const getData = () => {
        fetch("https://api.adviceslip.com/advice")
            .then((response) => response.json())
            .then((data) => {
                setData(data.slip.advice);
            });
    }
 
    useEffect(() => {
        getData();
    }, []);
 
    window.addEventListener("beforeunload", (event) => {
        getData();
        console.log("API call before page reload");
    });
 
    window.addEventListener("unload", (event) => {
        getData();
        console.log("API call after page reload");
    });
 
    return (
        <div>
            <h1>GeeksforGeeks</h1>
            <h3>{data}</h3>
        </div>
    );
}
 
export default App;


Steps to run the Application: Use this command in the terminal in project directory.

npm start

Output: This output will be visible on http://localhost:3000/ on the browser window.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads