replace local storage with cookie

This commit is contained in:
fmtabbara
2022-02-16 12:23:44 +00:00
parent b269cdae31
commit bd68797432
2 changed files with 37 additions and 4 deletions
+6 -4
View File
@@ -2,8 +2,8 @@ import { createContext, useEffect, useState } from 'react'
import ClientValidator, {
nativeToPrintable,
} from '@nymproject/nym-validator-client'
import { useLocalStorage } from '../hooks/useLocalStorage'
import { handleError } from '../utils'
import { useCookie } from '..//hooks/useCookie'
const { VALIDATOR_ADDRESS, MNEMONIC, TESTNET_URL_1, ACCOUNT_ADDRESS } =
process.env
@@ -70,8 +70,10 @@ export const GlobalContextProvider: React.FC = ({ children }) => {
if (error) console.error(error)
}, [error])
const [hasMadePreviousRequest, setHasMadePreviousRequest] =
useLocalStorage<boolean>('hasUsedFaucet', false)
const [hasMadePreviousRequest, setHasMadePreviousRequest] = useCookie(
'hasUsedFaucet',
false
)
const getBalance = async () => {
setLoadingState({ isLoading: true, requestType: EnumRequestType.balance })
@@ -113,7 +115,7 @@ export const GlobalContextProvider: React.FC = ({ children }) => {
{ amount: unymts, denom: 'unymt' },
])
setTokenTransfer({ address, amount: nymts })
setHasMadePreviousRequest(true)
setHasMadePreviousRequest(true, 1)
} catch (e) {
setError(handleError(e as Error))
}
+31
View File
@@ -0,0 +1,31 @@
import React, { useState } from 'react'
const getItem = (key: string) =>
document.cookie.split('; ').reduce((total, currentCookie) => {
const item = currentCookie.split('=')
const storedKey = item[0]
const storedValue = item[1]
return key === storedKey ? decodeURIComponent(storedValue) : total
}, '')
const setItem = (key: string, value: string, numberOfMinutes: number) => {
const now = new Date()
// set the time to be now + numberOfMinutes
now.setTime(now.getTime() + numberOfMinutes * 60 * 1000)
document.cookie = `${key}=${value}; expires=${now.toUTCString()}; path=/`
}
export const useCookie = (key: string, defaultValue: any) => {
const getCookie = () => getItem(key) || defaultValue
const [cookie, setCookie] = useState(getCookie())
const updateCookie = (value: string, numberOfDays: number) => {
setCookie(value)
setItem(key, value, numberOfDays)
}
return [cookie, updateCookie]
}