In this article, we will learn to send API call before the page reloads or close using ReactJS.
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 close so that we have the updated result from the API.
Implementation: Below is the step-by-step implementation of the above approach.
Step 1: Open the terminal and type the following command to create a react app. Change the <folder-name> to whatever you want, and press enter.
npx create-react-app <folder-name>
Step 2: Open the folder inside the code editor, and delete all the files inside the “src” folder except the index.js file.
Step 3: Delete all the files inside the public folder. Don’t worry we will create these files later according to our needs.
Project Structure: We have a simple project structure, we have a package.json & package-lock.json file which contains the details about the module installed inside this project. Then we have node_modules which contains the actual module and an “index.js” file inside “src”, our main server file.
Step 4: Create a file “index.js” inside the “public” folder and write the following code.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < meta name = "viewport" content = "width=device-width,initial-scale=1" /> < title >React App</ title > </ head > < body > < div id = "root" ></ div > </ body > </ html > |
This is a basic HTML code, inside we have an “id” root when you open the “index.js” file you will see that the react mount everything to this id everything we do inside our components will show here.
Make sure that your “index.js ” looks like this:
Javascript
import React from 'react' ; import ReactDOM from 'react-dom/client' ; import App from './App' ; const root = ReactDOM.createRoot(document.getElementById( 'root' )); root.render( <React.StrictMode> <App /> </React.StrictMode> ); |
Step 5: By default “index.js” mount the App component which we just deleted, so let’s create “App.js” components. Components in React.js are nothing but a function that returns HTML tags. Let’s make a function that returns the h1 heading, “neveropen”.
Javascript
function App() { return ( <div> <h1>neveropen</h1> </div> ); } export default App; |
Step 6: Inside “App.js” let’s use React state to create a state variable to which we will save the data fetch from API. We have set the default data as “Loading…”.
const [data, setData] = useState("Loading...");
Step 7: We have to create a function, inside which we will use the fetch method to fetch data from API, and set it to the data using the setData method. and then we use useEffect to call this function automatically after rendering the component.
Javascript
const getData = () => { .then((response) => response.json()) .then((data) => { setData(data.slip.advice); }); } useEffect(() => { getData(); }, []); |
Step 8: Then we will use the windows object and add an event listener which triggers before the page load, and a listener which triggers just after the page load, inside this listener callback we will just call the function which fetches the data from API and log the respective message so that we will trace its working on the console.
Javascript
window.addEventListener( "beforeunload" , (event) => { getData(); console.log( "API call before page reload" ); }); window.addEventListener( "unload" , (event) => { getData(); console.log( "API call after page reload" ); }); |
In addition, you can use the data state variable to print the result we get from the API call.
<h3>{data}</h3>
Completed Code:
App.js
Javascript
import { useState, useEffect } from "react" ; function App() { const [data, setData] = useState( "Loading..." ); const getData = () => { .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>neveropen</h1> <h3>{data}</h3> </div> ); } export default App; |
Output: