I created custom hooks, which allows to fetch the API using two request methods 'GET' and 'POST'.
Use cases:
const { data: fetchData, loading: fetchLoading, error: fetchError } = useFetch('/url');
const { data: postData, loading: postLoading, error: postError, post } = useFetch('/url', 'POST');
<DisplayData data={fetchData} />
<Button onClick={()=> post({id:4, name: 'jody'})} />
useFetch.js:
const useFetch = (url, method) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
if (!url || url.length === 0) {
console.error('Missing url');
if (!error) setError(true);
return { error };
}
const runFetchProcess = async (data) => {
const requestMethod = method === 'POST' ? 'POST' : 'GET';
let requestHeader = { headers: { 'Content-Type': 'application/json' }, method: requestMethod };
if (data) {
requestHeader.body = JSON.stringify(data);
}
try {
const response = await fetch(url, requestHeader);
const responseData = await response?.json();
if (!response.ok) {
setLoading(false);
setError(true);
throw Error('something wrong here mate');
} else {
setData(responseData);
setLoading(false);
}
} catch (e) {
setError(true);
console.error('useFetch.js', e);
} finally {
setLoading(false);
}
};
const post = (data) => {
if (!data) return;
runFetchProcess(data);
};
useEffect(() => {
if (method) return;
runFetchProcess();
}, []);
return { data, loading, error, post };
};
export default useFetch;
Please have a look my code. Looking forward to have some great feedback.