In earlier versions of our React application, we used the fetch API to retrieve data from external sources. However, fetch may not be supported in older browsers or headless testing environments. To address this, we can use Axios, a stable and widely adopted third-party library for making HTTP requests.
First, install Axios via npm:
npm install axiosThen import it into your App.jsx file:
import axios from 'axios';Replace fetch with axios.get() in your data-fetching function:
const handleFetchStories = React.useCallback(() => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
axios
.get(url)
.then((result) => {
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.data.hits,
});
})
.catch(() =>
dispatchStories({ type: 'STORIES_FETCH_FAILURE' })
);
}, [url]);To improve readability, refactor the function using async/await:
const handleFetchStories = React.useCallback(async () => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
try {
const result = await axios.get(url);
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.data.hits,
});
} catch {
dispatchStories({ type: 'STORIES_FETCH_FAILURE' });
}
}, [url]);Using async/await makes the code easier to follow and avoids deeply nested then chains. The try/catch block handles errors gracefully.
Using third-party libraries like Axios in React improves stability and scalability. Combined with async/await, your data-fetching logic becomes more readable and maintainable. These techniques are essential for building robust, real-world React applications.