Persist user interactions (#7)

* persist all user interactions

* move localstorage logic to custom hook

* hook rewrite
This commit is contained in:
Matthias Kretschmann 2024-04-16 13:04:00 +02:00 committed by GitHub
parent 0d08ba807b
commit ef1241e292
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 51 additions and 8 deletions

View File

@ -1,16 +1,15 @@
'use client'
import { useState } from 'react'
import { useDebounce } from 'use-debounce'
import { ratioOceanToAsi, ratioAgixToAsi, ratioFetToAsi } from '@/constants'
import { usePrices } from '@/features/prices'
import { getTokenBySymbol } from '@/lib'
import { FormAmount, Result } from '@/features/strategies'
import { FormAmount, Result, usePersistentState } from '@/features/strategies'
import stylesShared from '@/features/strategies/styles/shared.module.css'
export function Buy() {
const { prices, isValidating, isLoading } = usePrices()
const [amount, setAmount] = useState(100)
const [amount, setAmount] = usePersistentState('buyAmount', 100)
const [debouncedAmount] = useDebounce(amount, 500)
return (

View File

@ -1,17 +1,24 @@
'use client'
import { useState } from 'react'
import { useDebounce } from 'use-debounce'
import { SwapResults } from './Results'
import { TokenSymbol } from '@/types'
import { type Market, FormAmount, FormMarket } from '@/features/strategies'
import {
type Market,
FormAmount,
FormMarket,
usePersistentState
} from '@/features/strategies'
import stylesShared from '@/features/strategies/styles/shared.module.css'
export function Swap() {
const [amount, setAmount] = useState(100)
const [amount, setAmount] = usePersistentState('swapAmount', 100)
const [debouncedAmount] = useDebounce(amount, 500)
const [tokenSymbol, setTokenSymbol] = useState<TokenSymbol>('OCEAN')
const [market, setMarket] = useState<Market>('all')
const [tokenSymbol, setTokenSymbol] = usePersistentState<TokenSymbol>(
'swapTokenSymbol',
'OCEAN'
)
const [market, setMarket] = usePersistentState<Market>('swapMarket', 'all')
return (
<div className={stylesShared.results}>

View File

@ -1 +1,2 @@
export * from './use-quote'
export * from './use-persistent-state'

View File

@ -0,0 +1,36 @@
'use client'
import { useState, useEffect, Dispatch, SetStateAction } from 'react'
function parse(value: string) {
try {
return JSON.parse(value)
} catch {
return value
}
}
export function usePersistentState<T>(
key: string,
initialState?: T | (() => T)
): [T, Dispatch<SetStateAction<T>>] {
const [state, setState] = useState<T>(initialState as T)
function changeValue(state: SetStateAction<T>) {
setState(state)
localStorage.setItem(key, JSON.stringify(state))
}
useEffect(() => {
const stored = localStorage.getItem(key)
if (!stored) {
setState(initialState as T)
localStorage.setItem(key, JSON.stringify(initialState))
} else {
setState(parse(stored))
}
}, [initialState, key])
return [state, changeValue]
}