Skip to content

Instantly share code, notes, and snippets.

@cristovao-trevisan
Last active July 2, 2024 18:11
Show Gist options
  • Save cristovao-trevisan/9e62222bd0a0ce41b9022b762c65abab to your computer and use it in GitHub Desktop.
Save cristovao-trevisan/9e62222bd0a0ce41b9022b762c65abab to your computer and use it in GitHub Desktop.
Using svelte/store with react hooks (useStore)
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