Skip to content

Instantly share code, notes, and snippets.

@pokorson
Last active August 2, 2017 13:04
Show Gist options
  • Save pokorson/58805a744865b2f046e33161be699c2c to your computer and use it in GitHub Desktop.
Save pokorson/58805a744865b2f046e33161be699c2c to your computer and use it in GitHub Desktop.
Simple api middleware for redux
export const fetchTransactions = () => {
return {
type: "API_FETCH",
config: {
type: ACTIONS.FETCH_TRANSACTIONS,
action: () => axios.get(/* sample url */),
transform: response => response.data.result,
},
};
};
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