Make an Http request on click in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

Make an Http request on click in React #

To make an http request on click in React:

  1. Set the onClick prop on an element.
  2. Every time the element is clicked, make an HTTP request.
  3. Update the state variables and render the data.
If you use axios, scroll down to the next code snippet.
App.js
import {useState} from 'react'; const App = () => { const [data, setData] = useState(); const [isLoading, setIsLoading] = useState(false); const [err, setErr] = useState(''); const handleClick = async () => { setIsLoading(true); try { const response = await fetch('https://reqres.in/api/users', { method: 'POST', body: JSON.stringify({ name: 'John Smith', job: 'manager', }), headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); console.log('result is: ', JSON.stringify(result, null, 4)); setData(result); } catch (err) { setErr(err.message); } finally { setIsLoading(false); } }; console.log(data); return ( <div> {err && <h2>{err}</h2>} <button onClick={handleClick}>Make request</button> {isLoading && <h2>Loading...</h2>} {data && ( <div> <h2>Name: {data.name}</h2> <h2>Job: {data.job}</h2> </div> )} </div> ); }; export default App;

react make request on click

If you need to make an HTTP GET request on button click in React, check out my other article - Fetch data on Button click in React.

The example shows how to make an HTTP Post request on button click in React.

We set the onClick prop on a button element, so every time the button gets clicked, the handleClick function gets invoked.

We marked the handleClick function as async, so we are able to use the await keyword to await Promises inside of it.

In the handleClick function, we wait for the POST http request to finish and update the state variables.

This example uses the native fetch API, but the concept applies if you're using the axios package as well.

Here is how you would make an http POST request on button click using the axios package.

If you decide to use axios, make sure you have the package installed by running npm install axios.

App.js
import {useState} from 'react'; import axios from 'axios'; const App = () => { const [data, setData] = useState(); const [isLoading, setIsLoading] = useState(false); const [err, setErr] = useState(''); const handleClick = async () => { setIsLoading(true); try { const {data} = await axios.post( 'https://reqres.in/api/users', {name: 'John Smith', job: 'manager'}, { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); setData(data); } catch (err) { setErr(err.message); } finally { setIsLoading(false); } }; console.log(data); return ( <div> {err && <h2>{err}</h2>} <button onClick={handleClick}>Make request</button> {isLoading && <h2>Loading...</h2>} {data && ( <div> <h2>Name: {data.name}</h2> <h2>Job: {data.job}</h2> </div> )} </div> ); }; export default App;

react make request on click

The example shows how to make an Http POST request on click using axios.

If you use axios, make sure you have the package installed by running npm install axios in the root directory of your project.

The syntax when using the axios package is a bit cleaner and we have to deal with less implementation details, but the concept is the same.

We have to set the onClick prop on a button element and make an HTTP request every time the button is clicked.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.