Skip to content

Commit 348383c

Browse files
committed
refactor: useStore & error checking
1 parent a2671b0 commit 348383c

3 files changed

Lines changed: 26 additions & 4 deletions

File tree

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
"react": "^16.7.0-alpha.0",
2929
"react-dom": "^16.7.0-alpha.0",
3030
"redux": "^4.0.1",
31-
"use-restate": "^0.0.9"
31+
"use-restate": "^0.0.10"
3232
},
3333
"devDependencies": {
3434
"@types/jest": "^23.3.10",
@@ -63,4 +63,4 @@
6363
"lint-staged": {
6464
"*.ts": "yarn run lint"
6565
}
66-
}
66+
}

src/index.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,21 @@ import shallowEqual from './shallowEqual';
55
export const RestateContext: React.Context<Store<any> | undefined> = React.createContext(undefined);
66
export const RestateProvider = RestateContext.Provider;
77

8-
export function useRestate<TState, TSelector>(selectFrom: (state: TState) => TSelector): TSelector {
8+
const useStore = () => {
99
const store = useContext(RestateContext);
1010

11+
if (!store) {
12+
throw new Error(
13+
'use-restate requires you to initiate your redux-like store - e.g <RestateProvider value={store} />',
14+
);
15+
}
16+
17+
return store;
18+
};
19+
20+
export function useRestate<TState, TSelector>(selectFrom: (state: TState) => TSelector): TSelector {
21+
const store = useStore();
22+
1123
const [restate, setRestate] = useState(() => selectFrom(store.getState()));
1224
const previousRestate = useRef({});
1325

@@ -39,7 +51,7 @@ export function useRestate<TState, TSelector>(selectFrom: (state: TState) => TSe
3951
}
4052

4153
export function useDispatch<TAction extends Action>(): Dispatch<TAction> {
42-
const store = useContext(RestateContext);
54+
const store = useStore();
4355

4456
return store.dispatch;
4557
}

yarn.lock

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8819,6 +8819,16 @@ url@^0.11.0:
88198819
punycode "1.3.2"
88208820
querystring "0.2.0"
88218821

8822+
use-restate@^0.0.10:
8823+
version "0.0.10"
8824+
resolved "https://registry.yarnpkg.com/use-restate/-/use-restate-0.0.10.tgz#2f2bceb5f569f3961ae1ef0ef326b8b6370c644d"
8825+
integrity sha512-w2aheIL5NXORBE77E0Qv0DZ1p6zSXY3J5rLqU0wK00yb9kbBnd5CATF3YF5HjuFpqnqZ7ttzXMOv4YfxEIBeOQ==
8826+
dependencies:
8827+
react "^16.7.0-alpha.0"
8828+
react-dom "^16.7.0-alpha.0"
8829+
redux "^4.0.1"
8830+
use-restate "^0.0.9"
8831+
88228832
use-restate@^0.0.9:
88238833
version "0.0.9"
88248834
resolved "https://registry.yarnpkg.com/use-restate/-/use-restate-0.0.9.tgz#cce76d72a7e88139b07bd7d730f4771465eed9ed"

0 commit comments

Comments
 (0)