The get and post methods inside the httpClient.js file are already asynchronous, as they use the async keyword and await for making HTTP requests. However, if you would like to use Promises instead of the async/await syntax, we can modify the httpClient like this:
// src/httpClient.js
import axios from 'axios';
const httpClient = axios.create({
baseURL: 'https://your-base-url.com/api/',
headers: {
'Content-Type': 'application/json',
},
});
httpClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
httpClient.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response && error.response.status === 401) {
// Handle unauthorized errors
}
return Promise.reject(error);
}
);
const get = (url, config = {}) => {
return httpClient
.get(url, config)
.then((response) => response.data)
.catch((error) => {
console.error(`Error fetching data from ${url}:`, error.message);
throw error;
});
};
const post = (url, data, config = {}) => {
return httpClient
.post(url, data, config)
.then((response) => response.data)
.catch((error) => {
console.error(`Error posting data to ${url}:`, error.message);
throw error;
});
};
export default {
...httpClient,
get,
post,
};
Now, the httpClient uses Promises explicitly instead of the async/await syntax. You can still use them the same way in your React components or services:
// src/exampleService.js
import httpClient from './httpClient';
export const fetchData = () => {
return httpClient.get('data-endpoint');
};
export const postData = (data) => {
return httpClient.post('post-endpoint', data);
};
In your component, you can also use the Promise syntax like this:
// src/App.js
import React, { useEffect, useState } from 'react';
import { fetchData, postData } from './exampleService';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetchData()
.then((fetchedData) => {
setData(fetchedData);
})
.catch((error) => {
console.error('Error loading data:', error.message);
});
}, []);
const handlePostData = () => {
const newData = { key: 'value' }; // Replace with the data you want to post
postData(newData)
.then((response) => {
console.log('Data posted successfully:', response);
})
.catch((error) => {
console.error('Error posting data:', error.message);
});
};
return (
<div>
<h1>Data</h1>
{!data && <p>Loading...</p>}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
<button onClick={handlePostData}>Post data</button>
</div>
);
}
export default App;