Skip to content

Instantly share code, notes, and snippets.

@adoji92
Last active Apr 29, 2020
Embed
What would you like to do?
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