Skip to content

Instantly share code, notes, and snippets.

@AllGistsEqual
Created February 22, 2021 20:04
Show Gist options
  • Save AllGistsEqual/ab77803581aaf97a42599ec539778031 to your computer and use it in GitHub Desktop.
Save AllGistsEqual/ab77803581aaf97a42599ec539778031 to your computer and use it in GitHub Desktop.
// File: src/redux/ducks/api.ts
export const apiMiddleware: Middleware = ({ dispatch }) => next => action => {
next(action)
if (apiRequest.match(action)) {
const {
url,
method,
headers,
onSuccess,
onError,
}: ApiRequestPayload<any> = action.payload // eslint-disable-line @typescript-eslint/no-explicit-any
fetch(`${API_HOST}${url}`, {
method,
headers
})
.then(response => response.json())
.then(reponseData => dispatch(apiSuccess(onSuccess, reponseData)))
.catch(error => { dispatch(apiError(onError, error.message))
})
return
}
if (apiSuccess.match(action)) {
const { onSuccess, data } = action.payload
dispatch(onSuccess(data))
}
if (apiError.match(action)) {
const { onError, message } = action.payload
dispatch(onError(message))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment