Skip to content
This repository has been archived by the owner on Jan 15, 2023. It is now read-only.

Commit

Permalink
started juliette-react refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
markostanimirovic committed Aug 16, 2020
1 parent 8550a9d commit dfe43c2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { useContext, useEffect, useMemo, useState } from 'react';
import { StoreContext } from './store-context';
import { StoreContext } from './contexts';
import { Store, Dispatch, Selector } from 'juliette';
import { distinctUntilChanged, skip, take } from 'rxjs/operators';

export function useStore<T, R>(selector: Selector<T, R>): [R, Dispatch] {
const store: Store<T> = useContext(StoreContext);
export function useStore<T = any>(): Store<T> {
const store = useContext(StoreContext);
if (!store) throw new Error('Store is not provided! Use StoreContext to provide it.');

return store;
}

export function useDispatch(): Dispatch {
const store = useStore();
return store.dispatch.bind(store);
}

export function useSelector<T, R>(selector: Selector<T, R>): R {
const store = useStore<T>();

const [state$, initialState] = useMemo(() => {
let initialState: R = null as any;
const state$ = store.select(selector).pipe(distinctUntilChanged());
Expand All @@ -21,5 +32,5 @@ export function useStore<T, R>(selector: Selector<T, R>): [R, Dispatch] {
return () => subscription.unsubscribe();
}, [state$]);

return [state, store.dispatch.bind(store)];
return state;
}
4 changes: 2 additions & 2 deletions projects/juliette-react/src/public-api.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './lib/store-context';
export * from './lib/use-store';
export * from './lib/contexts';
export * from './lib/hooks';

0 comments on commit dfe43c2

Please sign in to comment.