Skip to content

Commit

Permalink
feat(react): useLocalStorage 兼容小程序
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jun 13, 2024
1 parent 6b8c3f2 commit de7d0ad
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 105 deletions.
45 changes: 0 additions & 45 deletions src/react/useLocalStorage.taro.test.ts

This file was deleted.

57 changes: 0 additions & 57 deletions src/react/useLocalStorage.taro.ts

This file was deleted.

30 changes: 27 additions & 3 deletions src/react/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,40 @@
import { Dispatch, SetStateAction, useCallback, useState } from 'react'
import { useLatest, useUpdateEffect } from 'react-use'
import { inMiniProgram } from '../utils'

const mp = inMiniProgram()
const storage: {
get: (key: string) => string | null
set: (key: string, value: string) => void
remove: (key: string) => void
} = mp
? {
get: key => mp.getStorageSync(key),
set: (key, value) => mp.setStorageSync(key, value),
remove: key => mp.removeStorageSync(key),
}
: {
get: key => localStorage.getItem(key),
set: (key, value) => localStorage.setItem(key, value),
remove: key => localStorage.removeItem(key),
}

export type UseLocalStorageResult<S> = readonly [
S,
Dispatch<SetStateAction<S>>,
() => void,
]

/**
* 已兼容小程序。
*/
export function useLocalStorage<S>(
key: string,
): UseLocalStorageResult<S | undefined>

/**
* 已兼容小程序。
*/
export function useLocalStorage<S>(
key: string,
initialState: S,
Expand All @@ -22,7 +46,7 @@ export function useLocalStorage<S>(
): UseLocalStorageResult<S | undefined> {
const getLocalStorageItem = useCallback(() => {
try {
const data = localStorage.getItem(key)
const data = storage.get(key)
if (data != null) {
return JSON.parse(data)
}
Expand All @@ -48,13 +72,13 @@ export function useLocalStorage<S>(
nextState = (nextState as any)(latestState.current)
}
setState(nextState)
localStorage.setItem(latestKey.current, JSON.stringify(nextState))
storage.set(latestKey.current, JSON.stringify(nextState))
},
[],
)

const reset: UseLocalStorageResult<S | undefined>[2] = useCallback(() => {
localStorage.removeItem(latestKey.current)
storage.remove(latestKey.current)
setState(latestInitialState.current)
}, [])

Expand Down

0 comments on commit de7d0ad

Please sign in to comment.