Skip to content

Commit ef36c14

Browse files
authored
Add useDispatcher and useStateEffect hooks (#199)
* Latest Core SDK * Add useDispatcher and useStateEffect hooks
1 parent b275353 commit ef36c14

File tree

4 files changed

+37
-3
lines changed

4 files changed

+37
-3
lines changed

.core/app/reactium-hooks.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ import('reactium-core/sdk').then(
124124

125125
Reactium.Hook.register(
126126
'sdk-init',
127-
async () => {
127+
async Reactium => {
128128
Reactium.State = new ReactiumSyncState(
129129
op.get(window, 'state', {}),
130130
);

.core/sdk/index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
} from '@atomic-reactor/reactium-sdk-core';
1414

1515
import { AppContext } from './named-exports';
16-
16+
import { useDispatcherFactory, useStateEffectFactory } from './named-exports';
1717
export * from '@atomic-reactor/reactium-sdk-core';
1818
export * from './named-exports';
1919

@@ -57,4 +57,9 @@ const apiHandler = {
5757
},
5858
};
5959

60-
export default new Proxy(SDK, apiHandler);
60+
const Reactium = new Proxy(SDK, apiHandler);
61+
62+
export const useDispatcher = useDispatcherFactory(Reactium);
63+
export const useStateEffect = useStateEffectFactory(Reactium);
64+
65+
export default Reactium;

.core/sdk/named-exports/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ export * from './i18n';
66
export * from './routing';
77
export * from './hookable-component';
88
export * from './app-context';
9+
export * from './useDispatcher';
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import _ from 'underscore';
2+
import cc from 'camelcase';
3+
import op from 'object-path';
4+
import {
5+
ComponentEvent,
6+
useEventEffect,
7+
} from '@atomic-reactor/reactium-sdk-core';
8+
9+
export const useDispatcherFactory = Reactium => ({ props, state }) => (
10+
type,
11+
obj,
12+
) => {
13+
if (!state) state = Reactium.State;
14+
15+
obj = _.isObject(obj) ? obj : {};
16+
17+
const evt = new ComponentEvent(type, obj);
18+
const cb = op.get(props, cc(`on-${type}`));
19+
20+
if (_.isFunction(cb)) state.addEventListener(type, cb);
21+
22+
state.dispatchEvent(evt);
23+
24+
if (_.isFunction(cb)) state.removeEventListener(type, cb);
25+
};
26+
27+
export const useStateEffectFactory = Reactium => (handlers = {}, deps) =>
28+
useEventEffect(Reactium.State, handlers, deps);

0 commit comments

Comments
 (0)