Hello! Today, we're going to uncover how web apps fetch data using APIs and the Fetch API in React. APIs retrieve data from systems, much like asking a waiter for takeout, while the Fetch API
, a promise-based mechanism, initiates network requests, similar to dialing for a delivery.
In essence, APIs act as messengers. They transport your request to a system and deliver the data you have ordered, much like how ordering a pizza over the phone works.
JavaScript1# Requesting weather data from the WeatherAPI - it's as simple as making a call! 2fetch('https://api.weatherapi.com/v1/current.json?q=Rome')
The Fetch API
requests data and then processes it when it arrives, similar to awaiting your pizza delivery.
JavaScript1fetch('https://api.weatherapi.com/v1/current.json?q=Rome') 2 .then(response => response.json()) 3 .then(data => console.log(data));
This process requests data from an API and converts it into a usable format — JSON.
Now, let's see how React, which uses components to divide the UI, utilizes the Fetch API
. In functional components, the useState
hook manages the data, often displaying a "Loading…" message while the data is being fetched.
JavaScript1function WeatherComponent() { 2 const [loading, setLoading] = useState(true); 3 const [weatherData, setWeatherData] = useState(null); 4 useEffect(() => { 5 fetch('https://api.weatherapi.com/v1/current.json?q=Rome') 6 .then(response => response.json()) 7 .then(data => { 8 setWeatherData(data); 9 setLoading(false); 10 }); 11 }, []) 12 if (loading) { 13 return <p>Loading...</p>; 14 } 15 return (<div> 16 <h1>Weather in {weatherData.location.name}</h1> 17 <p>{weatherData.current.condition.text}</p> 18 </div> 19 ) 20} 21export default WeatherComponent;
The useEffect
hook performs operations, such as fetching data, which cannot be done during rendering.
Once the data has been fetched, it is stored in the weatherData
state variable. A "Loading…" message is displayed until the data has been fetched; afterward, the data is shown. This check ensures that the data is displayed only once it has been fetched and is ready to be viewed.
Bravo! We have explored APIs, the Fetch API
, and their use in React for retrieving and displaying data. Remember to apply these lessons in upcoming practice exercises. Keep practicing for mastery in handling APIs in React. Happy coding!