Skip to content

Instantly share code, notes, and snippets.

@MiCurran
Created May 21, 2022 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiCurran/6d13c201966e885d10c05e5edc7098b0 to your computer and use it in GitHub Desktop.
Save MiCurran/6d13c201966e885d10c05e5edc7098b0 to your computer and use it in GitHub Desktop.
import axios from 'axios';
import { useEffect, useState } from 'react';
const useAPI = (path, options) => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const makeCall = async (path, options) => {
let callResults = {};
setLoading(true);
const params = {
headers: {
'Content-Type': 'application/json',
}
};
try {
callResults = await axios.get(path, params);
if (callResults.request.status === 200 && callResults?.data.success === false) {
setError(
callResults.data.message ||
options.errorMessage ||
'Error making call.'
);
}
setData(callResults.data)
setLoading(false);
return callResults.data;
} catch (e) {
console.error(e);
setError(e)
setLoading(false);
return (e);
}
};
useEffect(() => {
makeCall(path, options);
}, [])
return {
loading, data, error
};
};
export default useAPI;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment