Skip to content

Instantly share code, notes, and snippets.

@yesmeck
Last active November 26, 2018 11:00
Show Gist options
  • Save yesmeck/c0bbc12b9c5d41d4965b384887a1e2a0 to your computer and use it in GitHub Desktop.
Save yesmeck/c0bbc12b9c5d41d4965b384887a1e2a0 to your computer and use it in GitHub Desktop.
useStore
interface State {
list: Trade[];
detail: Trade | null;
}
const initialState = {
list: [],
detail: null,
};
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'list':
return { ...state, list: action.payload };
case 'detail':
return { ...state, detail: action.payload };
default:
return state;
}
}
export default function useStore(init: Partial<State>) {
const [state, dispatch] = useReducer<State, Action>(reducer, {
...initialState,
...init,
});
const fetchTrade = async (tradeId: string) => {
const { success, data } = await request.get<ResponseData<Trade[]>>(`/trades/${tradeId}`);
dispatch({
type: 'detail',
payload: data,
});
}
const fetchTrades = async (tradeType?: TradeType) => {
const { data } = await request.get<ResponseData<Trade[]>>('/trades', {
params: {
tradeType,
},
});
dispatch({
type: 'list',
payload: data,
});
}
return {
state,
dispatch,
fetchTrade,
fetchTrades,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment