Fetching Random User Data
In this example, we’ll create a React component called RandomUserData that fetches random user data from the Random Data API. The component will utilize the useState and useEffect hooks to manage state and handle the data fetching process respectively. Once the data is fetched, it will be displayed on the screen.
- We import React, useState, and useEffect from the ‘react’ package.
- The RandomUserData functional component is created to encapsulate the logic for fetching and displaying random user data.
- We define a state variable userData using the useState hook, initialized to null as we initially don’t have any user data.
- Within the useEffect hook, we perform a fetch request to the Random Data API endpoint that provides random user data.
- Upon receiving a response, we convert it to JSON format and update the userData state with the fetched data using the setUserData function.
- In the component’s return statement, we conditionally render user information once it’s available. This prevents errors due to accessing undefined data before the fetch completes.
Example: This example implements the above-mentioned approach
Javascript
/* RandomUserData.js */ import React, { useState, useEffect } from 'react' ; function RandomUserData() { const [userData, setUserData] = useState( null ); useEffect(() => { fetch( 'https://random-data-api.com/api/users/random_user' ) .then(response => response.json()) .then(data => setUserData(data)); }, []); return ( <div> {userData && ( <div> <h2>User Information</h2> <p> Name: {userData.first_name} {userData.last_name} </p> <p> Email: {userData.email} </p> { /* Add more user data fields as needed */ } </div> )} </div> ); } export default RandomUserData; |
Output:
Fetching Data from an API with useEffect and useState Hook
In modern web development, integrating APIs to fetch data is a common task. In React applications, the useEffect and useState hooks provide powerful tools for managing asynchronous data fetching. Combining these hooks enables fetching data from APIs efficiently.
This article explores how to effectively utilize these hooks to fetch data from an API, focusing on the Random Data API for practical examples