Skip to content

Commit

Permalink
feat: support react store to states
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr.Mao committed Jun 13, 2024
1 parent 3ae4f07 commit 7963fc3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/react-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"dist"
],
"scripts": {
"build": "ptsup src/index.ts --dts"
"build": "ptsup src --dts"
},
"dependencies": {
"mitt": "^3.0.1",
Expand Down
1 change: 1 addition & 0 deletions packages/react-utils/src/valtio/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './storeToState'
export * from './proxyWithPersistant'
export * from './storeToStates'
24 changes: 24 additions & 0 deletions packages/react-utils/src/valtio/storeToStates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/* eslint-disable max-statements-per-line */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { useSnapshot } from 'valtio'

export type StoreToStates<S> = {
[K in keyof S]: [S[K], (value: S[K]) => void]
}

export function storeToStates<S extends object>(store: S): StoreToStates<S> {
const snapshot = useSnapshot(store) as any
const states = {} as StoreToStates<S>

function toState(key: string) {
const get = () => snapshot[key]
// @ts-expect-error
const set = (value: any) => { store[key] = value }
return [get(), set] as const
}
for (const key of Object.keys(snapshot))
// @ts-expect-error
states[key] = toState(key)

return states
}

0 comments on commit 7963fc3

Please sign in to comment.