Last active
October 23, 2019 19:26
-
-
Save sisisin/38135f66185e32432f8092efc50536b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useAppActions } from 'hooks/useAppDispatch'; | |
import React, { useEffect } from 'react'; | |
export const Component = () => { | |
// ActionCreatorの集合を持ったオブジェクトを渡すとdispatch関数にラップされて返ってくる | |
const { initialize } = useAppActions(componentAggregate.creators); | |
useEffect(() => { | |
initialize(); | |
}, [initialize]); | |
return <div>hoge</div>; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ActionType } from 'redux-aggregate/typings/commons'; | |
import { ActionCreators } from 'redux-aggregate/typings/createAggregate'; | |
import { useMemo } from 'react'; | |
import { useDispatch } from 'react-redux'; | |
type Actions<T> = { | |
[ActionKey in keyof ActionCreators<T>]: ActionCreators<T>[ActionKey] extends () => { | |
type: ActionType; | |
} | |
? () => void | |
: ActionCreators<T>[ActionKey] extends (payload: infer PayloadType) => any | |
? (payload: PayloadType) => void | |
: never; | |
}; | |
export function useAppActions<T>(actionCreators: ActionCreators<T>): Actions<T> { | |
const dispatch = useDispatch(); | |
const dispatchers: any = {}; | |
Object.entries(actionCreators).forEach(([key, actionCreator]: [string, any]) => { | |
dispatchers[key] = (...args: any) => { | |
dispatch(actionCreator(...args)); | |
}; | |
}); | |
return useMemo(() => dispatchers, [actionCreators]); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useSelector } from 'react-redux'; | |
import { AppState } from '../store'; | |
// 型情報としてアプリ全体のStateを当て込んであげている | |
// js的には単に `useAppSelector` という別名の変数に代入してるだけ。 | |
export const useAppSelector: <TSelected>( | |
selector: (state: AppState) => TSelected, | |
equalityFn?: (left: TSelected, right: TSelected) => boolean, | |
) => TSelected = useSelector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment