Reputation: 303
I am writing my first custom middleware and slightly clueless to what is going on. My objective is to check if any action receives a network error, if so console.log it.
import { Middleware, MiddlewareAPI, Dispatch, Action } from "redux"
export const logger: Middleware = <S>(api: MiddlewareAPI<S>) => (
next: Dispatch<S>
) => <A extends Action>(action: A): A => {
console.log("Before")
const result = next(action)
if (action.type.HTTPStatus) {
console.log("HERE IS AN ERROR")
}
console.log("After", api.getState())
return result
}
The action.type.HTTPStatus does not work. I've been trying to filter the actions based on action.type but am not sure how to do it. It seems everything I attach to action.type.whatever doesn't break anything but doesn't do anything either. Here is an example of an API action.
export const getTelevisionChannels = (televisionIds: string[]) => async (
dispatch: Dispatch<AppState>
) => {
try {
const response = await API.post(
"/Channels/querys/status",
{ body: JSON.stringify({ televisionIds }) },
true,
dispatch
)
const televisionChannels = await response.json()
televisionChannels.map((televisionChannel: any) =>
dispatch(
getChannelsSuccess(televisionChannel.televisionId, televisionChannel.channels)
)
)
} catch (err) {
dispatch(push("/404"))
console.log(err)
}
}
I do have a goal to deal with this error with a separate Dispatch component with its own reducer and action but first I need to be able to get this middleware working.
Upvotes: 0
Views: 867
Reputation: 7671
I wrote a apiMiddleware recently, so here is the simplified version. What you want is to grab the error when there's an API issue and then dispatch an error action { type: errorType }
. Then you need a reducer to process these changes.
export default function createApiMiddleware(axios) {
return ({ getState }) => next => action => {
const api = action[CALL_API]
if (!api) {
return next(action)
}
const obj = {}
const { actionPrefix, types, method, host, url, onSuccess, ...props } = api
const prefix = actionPrefix || ''
const [startedType, successType, errorType] = types ? types : ACTION_KEYS.map(v => prefix + v)
next({ type: startedType })
obj.method = method || 'get'
obj.url = host ? (host + url) : url
const onSuccessOps = Object.assign({}, defaultOnSuccess, onSuccess)
const { responseBody } = onSuccessOps
const afterSuccess = (payload) => {
const { customActions } = onSuccessOps
customActions.forEach(type => {
next({ type, payload })
})
}
return axios(
Object.assign(obj, { ...props })
).then(res => {
const payload = responseBody(res)
next({ type: successType, payload })
afterSuccess(payload)
}, err => {
next({ type: errorType, payload: err })
})
}
}
export default function createApiReducer(actionPrefix, options) {
const ops = Object.assign({}, defaultOptions, options)
const initialState = {
data: [],
isLoaded: false,
isLoading: ops.loadOnStart,
error: null,
}
return (state = initialState, action) => {
const custom = ops.customActions[action.type]
if (custom) {
return custom(state)
}
switch (action.type) {
case `${actionPrefix}Loading`:
return {
...state,
isLoading: true,
error: null
}
case `${actionPrefix}Error`:
return {
...state,
isLoading: false,
error: action.payload
}
case `${actionPrefix}Success`:
return {
...state,
isLoading: false,
isLoaded: true,
error: null,
data: action.payload
}
default:
return state
}
}
}
Since you want a middleware, therefore I put it here as a reference, normally you would just want to dispatch couple of actions for one API in any redux text book. Hope this helps.
Upvotes: 1