From eca60f29f897d1085579dec23d1c571d9ba84420 Mon Sep 17 00:00:00 2001 From: Nikita Kuznetsov Date: Wed, 10 Jan 2024 20:24:52 +0100 Subject: [PATCH] Cache country code from api --- packages/uikit/src/state/country.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/uikit/src/state/country.ts b/packages/uikit/src/state/country.ts index b421ba58c..b9619355a 100644 --- a/packages/uikit/src/state/country.ts +++ b/packages/uikit/src/state/country.ts @@ -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'; @@ -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(url); + if (country) return country; + + const response = await fetch(url); const json: CountryIs = await response.json(); + await sdk.storage.set(url, json.country); return json.country; } catch (e) { return null; @@ -26,8 +32,9 @@ export const useCountrySetting = () => { }; export const useAutoCountry = () => { + const sdk = useAppSdk(); return useQuery([QueryKey.country, 'detect'], async () => { - return await getMyCountryCode(); + return await getMyCountryCode(sdk); }); }; @@ -36,7 +43,7 @@ export const useUserCountry = () => { return useQuery([QueryKey.country], async () => { let code = await sdk.storage.get(AppKey.COUNTRY); if (!code) { - code = await getMyCountryCode(); + code = await getMyCountryCode(sdk); } return code; });