React.js common service example
- Get link
- X
- Other Apps
In React.js, services are commonly used for making API requests, handling state management, or performing specific logic that can be reused throughout the application. A common service might interact with an API to fetch, post, or update data.
Let’s go through an example where we create a common API service that we can use in our React components to fetch data from a remote server.
Common API Service Example in React.js
In this example, we will create a service that handles API requests using Axios, a popular HTTP client for making requests in JavaScript. This service will be reusable across different components.
Steps to Create a Common API Service:
- Set up Axios
- Create a service for making API requests
- Use the service in a React component
1. Set up Axios
First, install Axios:
bashnpm install axios
Axios will help us make HTTP requests easily.
2. Creating a Common API Service
Create a folder called services
in the src
folder of your React app. Inside that folder, create a file named apiService.js
.
javascript// src/services/apiService.js
import axios from 'axios';
// Create an Axios instance with default configurations
const apiClient = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com', // Example API (you can replace it with your API)
headers: {
'Content-Type': 'application/json',
},
});
// GET request to fetch data from the API
const get = async (endpoint) => {
try {
const response = await apiClient.get(endpoint);
return response.data; // Return the response data
} catch (error) {
console.error('API GET Error: ', error);
throw error; // Throw error to be handled in the component
}
};
// POST request to send data to the API
const post = async (endpoint, data) => {
try {
const response = await apiClient.post(endpoint, data);
return response.data;
} catch (error) {
console.error('API POST Error: ', error);
throw error;
}
};
// Export the API service methods
export default {
get,
post,
};
Explanation:
- Axios Instance (
apiClient
): We create an Axios instance with a defaultbaseURL
(in this case, the JSONPlaceholder API) for consistency across requests. get
Method: Makes a GET request to the specified endpoint and returns the data.post
Method: Sends data to the specified endpoint using a POST request.- Error Handling: Errors are logged, and the error is rethrown so that the calling component can handle it.
3. Using the API Service in a React Component
Now let’s use the API Service to fetch data and display it in a React component.
App.js (Fetching Posts Example)
javascript// src/App.js
import React, { useEffect, useState } from 'react';
import apiService from './services/apiService'; // Import the API service
const App = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
// Fetch posts when the component mounts
useEffect(() => {
const fetchPosts = async () => {
try {
const data = await apiService.get('/posts'); // Fetch posts from the API
setPosts(data); // Set the posts in the state
setLoading(false); // Stop loading after data is fetched
} catch (err) {
setError('Failed to fetch posts'); // Handle any errors
setLoading(false);
}
};
fetchPosts();
}, []);
return (
<div className="App">
<h1>Posts</h1>
{loading && <p>Loading...</p>}
{error && <p style={{ color: 'red' }}>{error}</p>}
<ul>
{posts.map(post => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
};
export default App;
Explanation:
useEffect
: This hook is used to fetch the data from the API when the component mounts.- State Management: We maintain three pieces of state:
posts
: Holds the list of posts fetched from the API.loading
: Displays a loading indicator while the data is being fetched.error
: Displays an error message if the API request fails.
- Rendering: After the data is fetched, the posts are displayed in a list.
4. POST Request Example
You can also use the post
method from the apiService.js
file to send data to an API.
Let’s modify the App.js
to include a simple form for creating a new post using a POST
request.
javascript// src/App.js
import React, { useState } from 'react';
import apiService from './services/apiService'; // Import the API service
const App = () => {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const newPost = {
title: title,
body: body,
userId: 1, // Example user ID (you can replace it)
};
try {
// Send POST request to create a new post
const createdPost = await apiService.post('/posts', newPost);
setMessage(`Post created with ID: ${createdPost.id}`);
setTitle('');
setBody('');
} catch (err) {
setMessage('Failed to create post');
}
};
return (
<div className="App">
<h1>Create Post</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Title:</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<div>
<label>Body:</label>
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
required
/>
</div>
<button type="submit">Create Post</button>
</form>
{message && <p>{message}</p>}
</div>
);
};
export default App;
Explanation:
- Form Handling: The form collects a title and body for the new post.
- POST Request: When the form is submitted, the
handleSubmit
function sends thenewPost
object to the API using theapiService.post
method. - Success and Error Handling: Upon successful post creation, a success message is shown with the post ID. If there is an error, an error message is displayed.
Final Thoughts
- Separation of Concerns: By creating a separate
apiService.js
file, we keep the logic for making API calls separated from the components, making the code cleaner and more maintainable. - Reusability: The
apiService
can now be reused across multiple components for different API requests (GET, POST, PUT, DELETE). - Error Handling: The service includes basic error handling, and the React components can display appropriate messages to the user.
This is a basic example of how you can structure a common API service in a React application. You can expand it by adding methods for PUT, DELETE requests, setting up authentication tokens, handling response headers, and more as per your application's requirements.
- Get link
- X
- Other Apps
Comments
Post a Comment