How to send API call before page reload or close using ReactJS ?
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.
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:
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, “GeeksforGeeks”.
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.
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.
In addition, you can use the data state variable to print the result we get from the API call.
Please Login to comment...