Skip to content

Commit

Permalink
refactor: Relax types for persist middleware (#2332)
Browse files Browse the repository at this point in the history
Right now, we're requiring new `StateStorage` implementations to forcefully return `void` from inside `setItem` and `removeItem`.

When using a library that returns the set value for `setItem` or `removeItem`, therefore returning  a `string`, it causes Typescript to fail, requiring some weird workarounds.

For example, when using `localforage` (https://github.com/localForage/localForage) one needs to do what we describe below. Notice the `void` keyword.

```typescript
const storage: StateStorage = {
   ...localForage,
   setItem: void localForage.setItem.bind(localForage)
}
```

Another, longer, alternative is

```typescript
const storage: StateStorage = {
   ...localForage,
   // Curly braces are required because we need to "return `void`"
   setItem: (name, value) => {
       localStorage.setItem(name, value)
  }
}
```

By changing the type implementation to ignore types - using unknown - we can simply use `localforage` - and similar libraries - as if we were using `window.localStorage`
  • Loading branch information
rafaeelaudibert authored Feb 17, 2024
1 parent 8c1a1f0 commit 7d2525e
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/middleware/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import type {

export interface StateStorage {
getItem: (name: string) => string | null | Promise<string | null>
setItem: (name: string, value: string) => void | Promise<void>
removeItem: (name: string) => void | Promise<void>
setItem: (name: string, value: string) => unknown | Promise<unknown>
removeItem: (name: string) => unknown | Promise<unknown>
}

export type StorageValue<S> = {
Expand All @@ -19,8 +19,8 @@ export interface PersistStorage<S> {
getItem: (
name: string,
) => StorageValue<S> | null | Promise<StorageValue<S> | null>
setItem: (name: string, value: StorageValue<S>) => void | Promise<void>
removeItem: (name: string) => void | Promise<void>
setItem: (name: string, value: StorageValue<S>) => unknown | Promise<unknown>
removeItem: (name: string) => unknown | Promise<unknown>
}

type JsonStorageOptions = {
Expand Down Expand Up @@ -401,7 +401,7 @@ const newImpl: PersistImpl = (config, baseOptions) => (set, get, api) => {
)
}

const setItem = (): void | Promise<void> => {
const setItem = () => {
const state = options.partialize({ ...get() })
return (storage as PersistStorage<S>).setItem(options.name, {
state,
Expand Down

0 comments on commit 7d2525e

Please sign in to comment.