Last active
July 2, 2024 18:11
-
-
Save cristovao-trevisan/9e62222bd0a0ce41b9022b762c65abab to your computer and use it in GitHub Desktop.
Using svelte/store with react hooks (useStore)
This file contains hidden or 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
interface Setter<T> { | |
(value: T): void | |
} | |
export function useStore <T> (store: Writable<T>) : [T, Setter<T>]{ | |
const initialValue: T = get(store); | |
const [value, setValue] = useState(initialValue); | |
useEffect(() => store.subscribe(setValue), []); | |
return [value, store.set]; | |
} | |
export function useReducerWithStore<S, A> (reducer: Reducer<S, A>, store: Writable<S>): [S, Setter<A>] { | |
const [state, set] = useStore(store); | |
const dispatch = (action: A) => set(reducer(state, action)); | |
return [state, dispatch]; | |
} | |
export function combineDispatchers<A> (dispatchArray: Setter<A>[]) : Setter<A> { | |
return action => dispatchArray.forEach(dispatch => dispatch(action)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment