Fetch data on Button click in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

Fetch data on Button click in React #

To fetch data on button click in React:

  1. Set the onClick prop on a button element.
  2. Every time the button 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({data: []}); 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: 'GET', headers: { 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}>Fetch data</button> {isLoading && <h2>Loading...</h2>} {data.data.map(person => { return ( <div key={person.id}> <h2>{person.email}</h2> <h2>{person.first_name}</h2> <h2>{person.last_name}</h2> <br /> </div> ); })} </div> ); }; export default App;

fetch data on button click

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 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 fetch data 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({data: []}); const [isLoading, setIsLoading] = useState(false); const [err, setErr] = useState(''); const handleClick = async () => { setIsLoading(true); try { const {data} = await axios.get('https://reqres.in/api/users', { headers: { Accept: 'application/json', }, }); console.log('data is: ', 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}>Fetch data</button> {isLoading && <h2>Loading...</h2>} {data.data.map(person => { return ( <div key={person.id}> <h2>{person.email}</h2> <h2>{person.first_name}</h2> <h2>{person.last_name}</h2> <br /> </div> ); })} </div> ); }; export default App;

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.