Skip to content

Instantly share code, notes, and snippets.

@oscaroceguera
Created January 10, 2020 20:15
Show Gist options
  • Save oscaroceguera/1a13d9907e48b02a57416b9727f63408 to your computer and use it in GitHub Desktop.
Save oscaroceguera/1a13d9907e48b02a57416b9727f63408 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
// https://www.robinwieruch.de/react-hooks-fetch-data
const useDataApi = () => {
const [items, setData] = useState();
const [url, setUrl] = useState();
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
let mounted = true;
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios.get(`http://localhost:5000/api/lands`);
if (mounted) {
setData(result.data);
}
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
return () => {
mounted = false;
};
}, []);
return [{ items, isLoading, isError }];
};
export default useDataApi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment