Skip to content

Instantly share code, notes, and snippets.

@dueka
Created January 13, 2021 06:54
Show Gist options
  • Save dueka/5488169c00aec32f9daf977da04e8e20 to your computer and use it in GitHub Desktop.
Save dueka/5488169c00aec32f9daf977da04e8e20 to your computer and use it in GitHub Desktop.
Custom react hook to fetch data from an API
export const useInvestmentTypes = () => {
const [investmentTypesData, setInvestmentTypesData] = useState([]);
const token = selectToken.data.token;
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchInvestmentsTypes = useCallback(() => {
const fetchInvestmentTypesData = async () => {
const req = async () => {
try {
setLoading(true);
const { data } = await axiosWithAuth(token).get(
`api/v1/investment-types`
);
setInvestmentTypesData(data.data.investmentTypes);
} catch ({ response }) {
setError(response);
} finally {
setLoading(false);
}
};
req();
};
fetchInvestmentTypesData();
}, [token]);
useEffect(() => {
fetchInvestmentsTypes();
}, [fetchInvestmentsTypes]);
return [investmentTypesData, fetchInvestmentsTypes, loading, error];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment