1. Setting Up axios
Begin by adding axios to your project dependencies:
npm install axios
2. Creating the HTTPGet Component
The following component encapsulates GET request logic and exposes data, loading state, and errors through a render prop pattern.
// src/components/DataFetcher.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const DataFetcher = ({ endpoint, queryParams, render }) => {
const [result, setResult] = useState(null);
const [isFetching, setIsFetching] = useState(true);
const [fetchError, setFetchError] = useState(null);
useEffect(() => {
const loadData = async () => {
setIsFetching(true);
setFetchError(null);
try {
const apiResponse = await axios.get(endpoint, { params: queryParams });
setResult(apiResponse.data);
} catch (err) {
setFetchError(err);
} finally {
setIsFetching(false);
}
};
loadData();
}, [endpoint, queryParams]);
return render({ result, isFetching, fetchError });
};
export default DataFetcher;
3. Consuming the DataFetcher Component
Use the component in your application by providing a render function that receives the request state:
// src/components/ArticleList.js
import React from 'react';
import DataFetcher from './DataFetcher';
const ArticleList = () => {
return (
<DataFetcher endpoint="https://jsonplaceholder.typicode.com/posts">
{({ result, isFetching, fetchError }) => {
if (isFetching) return <p>Fetching data...</p>;
if (fetchError) return <p>Something went wrong: {fetchError.message}</p>;
return (
<section>
<h2>Articles</h2>
<ul>
{result.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</section>
);
}}
</DataFetcher>
);
};
export default ArticleList;
4. Integrating with Redux Provider
Wrap your application with the Redux Provider if state management is required:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import ArticleList from './components/ArticleList';
const Application = () => (
<Provider store={store}>
<ArticleList />
</Provider>
);
ReactDOM.render(<Application />, document.getElementById('root'));