Fetching data using async/await syntax
There are three ways to write asynchronous codes in vanilla JavaScript: callbacks, promises, and async/await
. In this section, we are going to focus on async
/await
and see how it can be used in React web applications. async/await
is an improvement on promises.
The following snippet explains how async/await
can be used to fetch data from an API using a promise-based approach:
import React, { useEffect, useState } from 'react';const App = () => { const [data, setData] = useState([]); const API_URL = "https://dummyjson.com/users"; const fetchSpeakers = async () => { try { const response = await fetch(API_URL); const data = await response.json(); ...