To make HTTP requests and fetch data from the Random User API in a React application, you can use the Fetch API or libraries like Axios. Here’s an example of how to use the Fetch API to fetch data from the Random User API in a React component:
Step 1: Set up a new React project
Create a new React project by running the following command in your terminal:
npx create-react-app random-user-app
Step 2: Create a User component
Inside the src
folder, create a new file called User.js
and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import React, { useState, useEffect } from 'react'; function User() { const [user, setUser] = useState(null); useEffect(() => { fetchUser(); }, []); const fetchUser = async () => { try { const response = await fetch('https://randomuser.me/api/'); const data = await response.json(); setUser(data.results[0]); } catch (error) { console.error('Error fetching user:', error); } }; if (!user) { return <div>Loading...</div>; } return ( <div> <img src={user.picture.large} alt={user.name.first} /> <h2>{`${user.name.first} ${user.name.last}`}</h2> <p>Email: {user.email}</p> <p>Username: {user.login.username}</p> </div> ); } export default User; |
In the code above, we define a User
component that fetches a random user from the API and displays their information.
We use the useState
hook to store the fetched user data. The initial state is set to null
.
The useEffect
hook is used to trigger the fetchUser
function when the component mounts ([]
dependency array).
Inside the fetchUser
function, we use the Fetch API to make a GET request to the Random User API (https://randomuser.me/api/
). We then extract the user data from the API response (data.results[0]
) and update the state using the setUser
function.
If the user data is still null
, we display a loading message. Once the user data is fetched, we render the user’s image, name, email, and username.
Step 3: Update the App component
Open the src/App.js
file and update it with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import React from 'react'; import User from './User'; function App() { return ( <div className="App"> <h1>Random User</h1> <User /> </div> ); } export default App; |
In the code above, we import the User
component and render it inside the App
component.
Step 4: Run the application
Save the files and start the development server by running the following command in the project directory: