Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by KaLisa Veer
To fetch data on button click in React:
onClick
prop on a button element.axios
, scroll down to the next code snippet.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;
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.
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
.
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.