From 2e57960f3fddd3b3f87b4d3a76d114c23141f2ea 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 | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/uikit/src/state/country.ts b/packages/uikit/src/state/country.ts index b421ba58c..efe7ea97e 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,14 @@ export interface CountryIs { ip: string; } -const getMyCountryCode = async () => { +const getMyCountryCode = async (sdk: IAppSdk) => { + const url = 'https://api.country.is'; + const country = await sdk.storage.get(url); + if (country) return country; try { const response = await fetch('https://api.country.is'); const json: CountryIs = await response.json(); + await sdk.storage.set(url, json.country); return json.country; } catch (e) { return null; @@ -26,8 +31,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 +42,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; });