Skip to content

Instantly share code, notes, and snippets.

@sisisin
Last active October 23, 2019 19:26
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 sisisin/38135f66185e32432f8092efc50536b2 to your computer and use it in GitHub Desktop.
Save sisisin/38135f66185e32432f8092efc50536b2 to your computer and use it in GitHub Desktop.
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>;
};
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]);
}
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