I am going through one tutorial of REST API and react, but I want to move a step ahead and write clean code. Therefore, I want to ask you for some help, so I could reuse hooks for different API requests.
With the tutorial, I've written this example where Hooks are used for saving API request statuses and think this is a good pattern I could reuse. Basically everything except const data = await API.getItems(token['my-token']) could be used for all/most API request I want to make. How should I reuse code with these technologies when building a clean API framework?
import { useState, useEffect } from 'react';
import { API } from '../api-service';
import { useCookies } from 'react-cookie';
function useFetch() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState();
const [token] = useCookies(['my-token']);
useEffect( ()=> {
async function fetchData() {
setLoading(true);
setError();
const data = await API.getItems(token['my-token'])
.catch( err => setError(err))
setData(data)
setLoading(false)
}
fetchData();
}, []);
return [data, loading, error]
}
export { useFetch }
BIG Thanks!