0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React カスタムフック 覚書

Last updated at Posted at 2021-10-15

React カスタムフック覚書

////// useCustomHook.ts
import { useReducer, useCallback } from 'react';

type State = {
  name: string;
  isLoading: boolean;
  errorMessage?: string;
};

type Handlers = {
  onSubmit: (name: State['name']) => void;
};

enum ActionTypes {
  OnSubmit = 'on-submit',
  OnSuccess = 'on-success',
  OnFailure = 'on-failure',
}

type Action =
  | { type: ActionTypes.OnSubmit, name: State['name'] }
  | { type: ActionTypes.OnSuccess }
  | { type: ActionTypes.OnFailure, errorMessage: Required<State['errorMessage']> };

const reducer: React.Reducer<State, Action> = (state: State, action: Action) => {
  const patch = (diff: Partial<State>): State => ({ ...state, ...diff });
  switch (action.type) {
    case ActionTypes.OnSubmit:
      return patch({
        isLoading: true,
        effect: {
          cmd: Cmd.hogeHoge, // api叩いたり
          args: [action.name],
          successActionCreator: () => ({ type: ActionTypes.OnSuccess }),
          failureActionCreator: (error: Error) => ({ type: ActionTypes.OnFailure, errorMessage: error.message }),
        },
      });
    case ActionTypes.OnSuccess:
      return patch({
        isLoading: false,
        effect: undefined,
      });
    case ActionTypes.OnFailure:
      return patch({
        isLoading: false,
        effect: undefined,
        errorMessage: action.errorMessage
      });
  }
};

const createInitialState = (name: State['name']): State => ({
  name,
  isLoading: false,
});

const useCustomHook = (name: State['name']): [State, Handlers] => {
  const [state, dispatch] = useReducer(reducer, name, createInitialState);
  const handlers: Handlers = {
    onSubmit: useCallback((name) => {
      dispatch({ type: ActionTypes.OnSubmit, name });
    }, []),
  };
  return [state, handlers];
};

export default useCustomHook;

////// useCmd.ts 頭良すぎでわけわからん このコードは別の方が作成
import { useEffect, Dispatch } from 'react';

export type Effect<F, Action> = F extends (...args: infer Params) => Promise<infer Result> ? {
  cmd: F;
  args: Params;
  successActionCreator: (result: Result) => Action;
  failureActionCreator: (e: Error) => Action;
} : never;

const useCmd = <F, Action>(dispatch: Dispatch<Action>, effect?: Effect<F, Action>) => {
  useEffect(() => {
    if (effect) {
      effect.cmd(...effect.args)
        .then(result => dispatch(effect.successActionCreator(result)))
        .catch((e: Error) => dispatch(effect.failureActionCreator(e)));
    }
  }, [dispatch, effect]);
};

export default useCmd;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?