1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00

persist user preferences through localStorage

This commit is contained in:
Matthias Kretschmann 2020-09-10 13:43:20 +02:00
parent c867253dd9
commit d5d9ce370b
Signed by: m
GPG Key ID: 606EEEF3C479A91F
2 changed files with 40 additions and 8 deletions

View File

@ -6,6 +6,7 @@ import Tabs from '../../../atoms/Tabs'
import Fixed from './Fixed'
import Dynamic from './Dynamic'
import { useField } from 'formik'
import { useUserPreferences } from '../../../../providers/UserPreferences'
const query = graphql`
query PriceFieldQuery {
@ -35,6 +36,7 @@ const query = graphql`
`
export default function Price(props: InputProps): ReactElement {
const { debug } = useUserPreferences()
const data = useStaticQuery(query)
const content = data.content.edges[0].node.childPagesJson.price
@ -89,9 +91,11 @@ export default function Price(props: InputProps): ReactElement {
return (
<div className={styles.price}>
<Tabs items={tabs} handleTabChange={handleTabChange} />
{debug === true && (
<pre>
<code>{JSON.stringify(field.value)}</code>
</pre>
)}
</div>
)
}

View File

@ -3,7 +3,8 @@ import React, {
useContext,
ReactElement,
ReactNode,
useState
useState,
useEffect
} from 'react'
declare type Currency = 'EUR' | 'USD'
@ -11,19 +12,46 @@ declare type Currency = 'EUR' | 'USD'
interface UserPreferencesValue {
debug: boolean
currency: Currency
setDebug: (value: boolean) => void
setCurrency: (value: string) => void
setDebug?: (value: boolean) => void
setCurrency?: (value: string) => void
}
const UserPreferencesContext = createContext(null)
const localStorageKey = 'ocean-user-preferences'
function getLocalStorage() {
const storageParsed =
window && JSON.parse(window.localStorage.getItem(localStorageKey))
return storageParsed
}
function setLocalStorage(values: UserPreferencesValue) {
return (
window &&
window.localStorage.setItem(localStorageKey, JSON.stringify(values))
)
}
function UserPreferencesProvider({
children
}: {
children: ReactNode
}): ReactElement {
const [debug, setDebug] = useState<boolean>(false)
const [currency, setCurrency] = useState<Currency>('EUR')
const localStorage = getLocalStorage()
// Set default values from localStorage
const [debug, setDebug] = useState<boolean>(
(localStorage && localStorage.debug) || false
)
const [currency, setCurrency] = useState<Currency>(
(localStorage && localStorage.currency) || 'EUR'
)
// Write values to localStorage on change
useEffect(() => {
setLocalStorage({ debug, currency })
}, [debug, currency])
return (
<UserPreferencesContext.Provider