Skip to content

Instantly share code, notes, and snippets.

@adoji92

adoji92/Counter.tsx

Last active Oct 30, 2019
Embed
What would you like to do?
import React, { useCallback } from 'react';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { myActions } from './my'
type CounterStateProps = {
num: number;
};
type CounterDispatchProps = {
updateNum: typeof myActions.updateNum;
};
type CounterOwnProps = {
title: string;
};
type CounterProps = CounterStateProps &
CounterDispatchProps &
CounterOwnProps & {
location: Location; // NOTE: injected by withRouter HoC
};
const Counter: React.FC<CounterProps> = props => {
const {
title,
num,
updateNum,
location: {
href,
},
} = props;
const handleIncreaseClick = useCallback(
() => {
updateNum(num + 1);
},
[num],
);
return (
<>
<h1>This is {title} Counter</h1>
<p>href: {href}</p>
<p>current count: {num}</p>
<button onClick={handleIncreaseClick}>increase</button>
</>
);
};
const enhance = compose<React.FC<CounterOwnProps>>(
connect<
CounterStateProps,
CounterDispatchProps,
CounterOwnProps,
any // 또는 state의 타입
>(
state => ({
num: state.my.num,
}),
myActions,
),
withRouter,
);
export default enhance(Counter);
import deepCopy from 'deep-copy';
import { createActionCreator, createReducer } from 'deox';
export type MyState = {
num: number;
};
export const initialState: MyState = {
num: 0,
};
export const myActions = {
updateNum: createActionCreator(
'my/UPDATE_NUM',
resolve => (newNum: number) => resolve(newNum),
),
};
const myReducer = createReducer(initialState, handleActions => [
handleAction(
actions.updateCounter,
(state, { payload }) => {
const newState = deepCopy(state);
newState.num = payload;
return newState;
},
),
]);
export default myReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment