ReactでDvaのモデルを簡単に使用
10190 ワード
import { EffectsCommandMap } from 'dva';
import { AnyAction, Reducer } from 'redux';
import {fetchGql} from "@/fetch";
export type Effect = (
action: AnyAction,
effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;
interface StateType {
[modalState:string]:any;
}
export interface ModelType {
namespace: string;
state: StateType;
subscriptions: {
[modalSubscriptions:string]:Function
}
effects: {
[modalEffect:string]: Effect;
};
reducers: {
[modalReducer:string]: Reducer<StateType>;
};
}
export const gqlState = (gqlApi: string, model: any):ModelType =>
Object.assign(
{
// :gql+Api (api )
namespace: `gql${gqlApi.replace(gqlApi[0], gqlApi[0].toUpperCase())}`,
effects: {
*[gqlApi + 'Effect']({ type, payload }: any, { put, call, select }: any) {
let ret;
try {
ret = yield call(fetchGql, payload);
} catch (e) {
alert(` gqlApi :${e.message}`);
}
yield put({ type: gqlApi, payload: ret.data[payload] });
},
},
reducers: {
[gqlApi](state: any, { payload }: any) {
alert(` reducers :${gqlApi}`);
},
},
},
model,
);