In this tutorial, you will learn how to fetch data from a backend API and display it in your React app. We will also show how to connect React to a Spring Boot backend.
Introduction
Most real-world applications need to interact with a backend server to get or send data. React provides several ways to fetch data, and the simplest is using the built-in fetch API or libraries like Axios.
1. Sample Backend API
Assume you have a Spring Boot backend running at http://localhost:8080/users which returns a JSON array of users:
[
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" }
]
2. Fetch Data in React
Update App.jsx to fetch users when the component mounts:
import { useEffect, useState } from 'react';
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('http://localhost:8080/users')
.then(response => response.json())
.then(data => setUsers(data))
.catch(error => console.error('Error fetching users:', error));
}, []);
return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name} - {user.email}</li>
))}
</ul>
</div>
);
}
export default App;
3. Explanation
useEffectruns after the component mounts, ideal for fetching data.fetch()makes an HTTP request to the backend API.response.json()converts the response to a JSON object.setUsers(data)updates the state, triggering a re-render to display the data.
4. Error Handling
Always handle errors in case the API fails:
.catch(error => console.error('Error fetching users:', error));
You can also display an error message to users using another state variable.
5. Using Axios (Optional)
You can also use Axios for cleaner syntax. Install it first:
npm install axios
Then replace fetch with:
import axios from 'axios';
useEffect(() => {
axios.get('http://localhost:8080/users')
.then(res => setUsers(res.data))
.catch(err => console.error(err));
}, []);
6. Summary
In this tutorial, you learned how to:
- Fetch data from a backend API using fetch and Axios
- Use
useEffectto trigger API calls - Update state and display dynamic data
- Handle errors gracefully
Next, in React Beginner 7, you will learn about routing to create multi-page applications.