Skip to content

Instantly share code, notes, and snippets.

@dongjinahn
Last active April 29, 2020 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongjinahn/c97b0ac5a32d874d0311592284da4362 to your computer and use it in GitHub Desktop.
Save dongjinahn/c97b0ac5a32d874d0311592284da4362 to your computer and use it in GitHub Desktop.
import { useTypedSelector } from '../../src/store';
import { useCallback } from 'react';
import { actions } from '../../src/store/reducers/counter';
import { useDispatch } from 'react-redux';
import { wrapWithDispatch } from '../../src/utils.ts';
export default function Counter() {
const counterActions = naiveWrapWithDispatch(useDispatch(), actions);
const count = useTypedSelector(state => state.counter);
const handleClickIncrement = useCallback(() => {
counterActions.increment();
}, []);
const handleClickDecrement = useCallback(() => {
counterActions.decrement();
}, []);
const handleClickReset = useCallback(() => {
counterActions.reset(0);
}, []);
return (
<div className="container-fluid">
counter template! {count}
<br />
<button onClick={handleClickIncrement}>+</button>
<button onClick={handleClickDecrement}>-</button>
<button onClick={handleClickReset}>reset</button>
</div>
);
}
import { useTypedSelector } from '../../src/store';
import { useCallback } from 'react';
import { counterActions } from '../../src/store/reducers/counter';
import { useDispatch } from 'react-redux';
export default function Counter() {
const dispatch = useDispatch();
const count = useTypedSelector(state => state.counter);
const handleClickIncrement = useCallback(() => {
dispatch(counterActions.increment());
}, []);
const handleClickDecrement = useCallback(() => {
dispatch(counterActions.decrement());
}, []);
const handleClickReset = useCallback(() => {
dispatch(counterActions.reset(0));
}, []);
return (
<div>
counter template! {count}
<br />
<button onClick={handleClickIncrement}>+</button>
<button onClick={handleClickDecrement}>-</button>
<button onClick={handleClickReset}>reset</button>
</div>
);
}
export function naiveWrapWithDispatch(dispatch, actions) {
const res = {};
Object.keys(actions).forEach(key => {
res[key] = function () {
dispatch(actions[key].apply(null, arguments));
};
});
return res;
}
import { Dispatch } from 'redux';
import { ActionCreator } from 'deox';
type ActionsType = { [key: string]: ActionCreator<string> };
export function wrapWithDispatch<T extends ActionsType>(dispatch: Dispatch, actions: T) {
const res = {};
Object.keys(actions).forEach(key => {
res[key] = function () {
dispatch(actions[key].apply(null, arguments));
};
});
return res as T;
}
return res as { [key in keyof T]: (...params: Parameters<T[key]>) => void };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment