improve local storage hook implementation
This commit is contained in:
parent
86994c4c46
commit
3acad86157
|
@ -1,6 +1,6 @@
|
||||||
import { SSR } from '@/lib/constants'
|
import { SSR } from '@/lib/constants'
|
||||||
import { useMe } from './me'
|
import { useMe } from './me'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useRef } from 'react'
|
||||||
import createTaskQueue from '@/lib/task-queue'
|
import createTaskQueue from '@/lib/task-queue'
|
||||||
|
|
||||||
const VERSION = 1
|
const VERSION = 1
|
||||||
|
@ -18,24 +18,24 @@ export default function useLocalStorage ({ database = 'default', namespace = ['d
|
||||||
const { me } = useMe()
|
const { me } = useMe()
|
||||||
if (!Array.isArray(namespace)) namespace = [namespace]
|
if (!Array.isArray(namespace)) namespace = [namespace]
|
||||||
const joinedNamespace = namespace.join(':')
|
const joinedNamespace = namespace.join(':')
|
||||||
const [storage, setStorage] = useState(openLocalStorage({ database, userId: me?.id, namespace }))
|
const storage = useRef(openLocalStorage({ database, userId: me?.id, namespace }))
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const currentStorage = storage
|
const currentStorage = storage.current
|
||||||
const newStorage = openLocalStorage({ database, userId: me?.id, namespace })
|
const newStorage = openLocalStorage({ database, userId: me?.id, namespace })
|
||||||
setStorage(newStorage)
|
storage.current = newStorage
|
||||||
if (currentStorage) currentStorage.close()
|
if (currentStorage)currentStorage.close()
|
||||||
return () => {
|
return () => {
|
||||||
newStorage.close()
|
newStorage.close()
|
||||||
}
|
}
|
||||||
}, [me, database, joinedNamespace])
|
}, [me, database, joinedNamespace])
|
||||||
|
|
||||||
return [{
|
return [{
|
||||||
set: storage.set,
|
set: (key, value) => storage.current.set(key, value),
|
||||||
get: storage.get,
|
get: (key) => storage.current.get(key),
|
||||||
unset: storage.unset,
|
unset: (key) => storage.current.unset(key),
|
||||||
clear: storage.clear,
|
clear: () => storage.current.clear(),
|
||||||
list: storage.list
|
list: () => storage.current.list()
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue