-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
40 lines (34 loc) · 1014 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//react-geolocate
import { useState, useEffect } from "react";
const useGeoLocation = (options = {}) => {
const [country, setCountry] = useState(options.country);
const [error, setError] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const api = options.api || "https://api.country.is";
useEffect(() => {
let isCancelled = false;
if (country || country === false) return;
async function fetchAPI() {
setIsLoading(true);
await fetch(api)
.then(res => {
if (!res.ok) {
throw Error(res.statusText);
return null;
}
return res.json();
})
.then(res => {
if (res && res.country && !isCancelled) setCountry(res.country);
})
.catch(err => setError(err))
.finally(() => setIsLoading(false));
}
fetchAPI();
return () => {
isCancelled = true;
};
}, []);
return { country, error, isLoading };
};
export default useGeoLocation;