Async event handlers for onClick events in React
In React, event handlers, or event handler functions, don't have to always be synchronous. We can create asynchronous event handlers for events like onClick
that perform an API request asynchronously.
Async event handlers allow us to do things like fetching data when a user click event occurs. Let's take a look at an example of an asynchronous event handler that does exactly this.
We'll start by by creating a React component where we'll define a button with an onClick
event. Then, we'll add an async
event handler for this button.
Clicking on the button will trigger the event handler that will fetch a list of countries, as well as the user's current country. This country data will be stored in component state so that it can be displayed by the component.
import { useState } from 'react';
const API_URL =
'https://valid.layercode.workers.dev/list/countries?format=select&flags=true&value=code';
type Country = {
key: string;
label: string;
};
const Countries = () => {
const [countries, setCountries] = useState<Country[]>([]);
const [selectedCountry, setSelectedCountry] = useState<Country | null>(
null
);
const handleClick = async () => {
try {
const response = await fetch(API_URL);
const json = await response.json();
setCountries(countries);
setSelectedCountry(userSelectValue);
} catch (error) {
console.log(`Error: ${error}`);
}
};
return (
<div>
<button onClick={handleClick}>Fetch Countries</button>
{selectedCountry && <p>You are in {selectedCountry.label}.</p>}
{countries.length > 0 && (
<>
<h3>List of countries</h3>
<ul>
{countries.map(({ label }) => (
<li>{label}</li>
))}
</ul>
</>
)}
</div>
);
};
export const App = () => {
return <Countries />;
};
We defined the API endpoint URL for this example as a constant outside the component. Then, we defined the type Country
to represent the data returned by the API endpoint.
The handleClick
function is an async
function that uses the Fetch API to request data from an API endpoint. The API endpoint that we used is flexible enough to return both a list of countries, and the user's current country. We stored both in the component's state using our state setter functions.
After the data fetching is complete, the selectedCountry
state variable will no longer be null
, causing it to be rendered to the screen. The countries
state variable will also have a length greater than zero, causing it to be rendered to the screen as an unordered list.
Demo
Conclusion
The example above shows how we can create an async event handler that performs an API request when a button is clicked in a React component.
You can swap out the API endpoint URL for any other API endpoint that you might need for your use case.