Skip to content

Commit

Permalink
fix countries API changed
Browse files Browse the repository at this point in the history
  • Loading branch information
alankilalank committed Mar 27, 2020
1 parent 9546f53 commit 39d1197
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
18 changes: 12 additions & 6 deletions src/components/CountryPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Error from './Error';
import Loading from './Loading';
import Stats from './Stats';
import useDataApi from '../hooks/useDataApi';
import { ICountryResponse } from '../types';
import { CountryResponse } from '../types';
import Row from './Row';

const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;
Expand Down Expand Up @@ -43,18 +43,23 @@ const WrapperSelect = styled.div`

const CountryPicker = () => {
const [selectedCountry, setSelectedCountry] = React.useState('');
const [countries, setCountries] = React.useState<string[]>([]);

const [{ data, isLoading, isError }] = useDataApi<ICountryResponse>({
const [{ data, isLoading, isError }] = useDataApi<CountryResponse>({
initUrl: `${API_ENDPOINT}/countries`,
defaultData: {},
});

React.useEffect(() => {
if (data && data.countries) {
const iso2 = data.countries.map(c => c.iso2);
setCountries(iso2);
}
fetch(`https://ipapi.co/country`)
.then(res => res.text())
.then(setSelectedCountry)
.catch(() => setSelectedCountry("ID"));
}, []);
.catch(() => setSelectedCountry('ID'));
}, [data]);

if (isLoading) {
return <Loading speed={300} />;
Expand All @@ -67,13 +72,14 @@ const CountryPicker = () => {
<Error message="There was a problem fetching countries" />
</Row>
)}
{data && data.iso3 && selectedCountry !== "" && (
{selectedCountry && (
<>
<WrapperSelect>
<ReactFlagsSelect
countries={countries}
searchable={true}
defaultCountry={selectedCountry}
onSelect={code => setSelectedCountry(data.iso3[code])}
onSelect={code => setSelectedCountry(code)}
/>
</WrapperSelect>
<Stats url={`${API_ENDPOINT}/countries/${selectedCountry}`} />
Expand Down
11 changes: 8 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ export interface StringMap {
[key: string]: string;
}

export interface ICountryResponse {
countries: Record<string, string>;
iso3: Record<string, string>;
export interface ICountry {
name: string;
iso2: string;
iso3: string;
}

export interface IStatsResponse {
Expand All @@ -19,6 +20,10 @@ export interface IStatsResponse {
lastUpdate: Date;
}

export type CountryResponse = {
countries: ICountry[];
};

export type UseDataApiArgs = {
initUrl: string;
defaultData?: any;
Expand Down

1 comment on commit 39d1197

@vercel
Copy link

@vercel vercel bot commented on 39d1197 Mar 27, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.