Last active
November 26, 2018 11:00
-
-
Save yesmeck/c0bbc12b9c5d41d4965b384887a1e2a0 to your computer and use it in GitHub Desktop.
useStore
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
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