Last active
August 2, 2017 13:04
-
-
Save pokorson/58805a744865b2f046e33161be699c2c to your computer and use it in GitHub Desktop.
Simple api middleware for redux
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
export const fetchTransactions = () => { | |
return { | |
type: "API_FETCH", | |
config: { | |
type: ACTIONS.FETCH_TRANSACTIONS, | |
action: () => axios.get(/* sample url */), | |
transform: response => response.data.result, | |
}, | |
}; | |
}; |
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
const apiFetch = ({ dispatch }) => next => async action => { | |
if (action.type !== "API_FETCH") return next(action); | |
const { type, action: apiAction, transform } = action.config; | |
dispatch({ type: `${type}_PENDING` }); | |
try { | |
const response = await apiAction(); | |
const data = transform ? transform(response) : response; | |
dispatch({ type: `${type}_SUCCESS`, payload: data }); | |
} catch (err) { | |
if (action.type === "API_FETCH") | |
dispatch({ type: `${type}_ERROR`, payload: error }); | |
throw err; | |
} | |
}; | |
export default apiFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment