Last active
May 5, 2019 13:44
-
-
Save shqld/d1fc0c0db6a25ddf761e12cfec90ac3e to your computer and use it in GitHub Desktop.
`useStore` hook for reading global state without binding actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'preact/hooks' | |
// or | |
import { useState, useEffect } from 'react' | |
import { Store } from 'unistore' | |
// or | |
import { Store } from 'redux' | |
const extract = (state: any, key: any) => { | |
if (!key) return state | |
if (Array.isArray(key)) { | |
return key.reduce((acc, k) => { | |
acc[k] = state[k] | |
return acc | |
}, {}) | |
} | |
return state[key] | |
} | |
type UseStore<K> = { | |
<T extends keyof K>(key: T): K[T] | |
<T extends Array<keyof K>>(key: T): Pick<K, T[number]> | |
(key?: undefined): K | |
} | |
export const createUseStore = <K>(store: Store<K>) => { | |
const useStore: UseStore<K> = <T>(key: T) => { | |
const [state, set] = useState(extract(store.getState(), key)) | |
useEffect( | |
() => | |
store.subscribe(() => { | |
set(extract(store.getState(), key)) | |
}), | |
[] | |
) | |
return state | |
} | |
return { | |
useStore, | |
} | |
} |
Author
shqld
commented
May 5, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment