Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache country code from external API #18

Merged
merged 1 commit into from
Jan 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions packages/uikit/src/state/country.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { IAppSdk } from '@tonkeeper/core/dist/AppSdk';
import { AppKey } from '@tonkeeper/core/dist/Keys';
import { useAppSdk } from '../hooks/appSdk';
import { QueryKey } from '../libs/queryKey';
Expand All @@ -8,10 +9,15 @@ export interface CountryIs {
ip: string;
}

const getMyCountryCode = async () => {
const getMyCountryCode = async (sdk: IAppSdk) => {
const url = 'https://api.country.is';
try {
const response = await fetch('https://api.country.is');
const country = await sdk.storage.get<string>(url);
if (country) return country;

const response = await fetch(url);
const json: CountryIs = await response.json();
await sdk.storage.set<string>(url, json.country);
return json.country;
} catch (e) {
return null;
Expand All @@ -26,8 +32,9 @@ export const useCountrySetting = () => {
};

export const useAutoCountry = () => {
const sdk = useAppSdk();
return useQuery<string | null, Error>([QueryKey.country, 'detect'], async () => {
return await getMyCountryCode();
return await getMyCountryCode(sdk);
});
};

Expand All @@ -36,7 +43,7 @@ export const useUserCountry = () => {
return useQuery<string | null, Error>([QueryKey.country], async () => {
let code = await sdk.storage.get<string>(AppKey.COUNTRY);
if (!code) {
code = await getMyCountryCode();
code = await getMyCountryCode(sdk);
}
return code;
});
Expand Down