Reputation: 417
The below code is my custom redux middleware. In the removeItemFlow function, the action.type === REMOVE_ITEM is not being executed even though I press on the delete button from the frontend and the type: REMOVE_ITEM and payload successfully execute but the middleware is not catching it. I have been wrestling with this for two days now so any help will be greatly appreciated. Thank you.
//Custom Redux Middleware
export const getItemsFlow = ({getState, dispatch}) => next => action => {
next(action);
if (action.type === GET_ITEMS) {
dispatch(apiGetRequest('/api/items/water/', setAuthorizationHeader(getState), FETCH_ITEMS_SUCCESS, FETCH_ITEMS_ERROR));
dispatch(loadingData());
}
};
export const processItemsCollection = ({dispatch}) => next => action => {
next(action);
if (action.type === FETCH_ITEMS_SUCCESS) {
dispatch(updateItems(action.payload.data));
}
};
export const removeItemFlow = ({getState, dispatch}) => next => action => {
next(action);
if(action.type === REMOVE_ITEM){
console.log(action.type)
dispatch(apiDeleteRequest(`/api/items/water/${action.payload.id}`, setAuthorizationHeader(getState), REMOVE_ITEM_SUCCESS, REMOVE_ITEM_ERROR));
}
};
export const itemsMdl = [getItemsFlow, processItemsCollection, removeItemFlow];
//Redux Store
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(
rootReducer,
composeEnhancers(
applyMiddleware(...itemsMdl, ...api),
)
);
Upvotes: 1
Views: 1042
Reputation: 67597
I have a few observations here. None of them are a direct solution to your issue, but they may ultimately point you towards an alternate approach that doesn't have this problem.
First, none of your custom middleware are actually returning the result of next(action)
. In this case, it's probably not breaking anything, but a good Redux middleware should always try to return the result it was given:
const result = next(action);
// do more logic here if you want to
return result;
Second, you don't need to separate this into three different middleware. You could do it as a single middleware with multiple conditions inside.
Third, this really feels like it doesn't need to be a custom middleware at all. There's nothing wrong with using custom Redux middleware, but in this case what you seem to be doing can be accomplished a lot more simply by using Redux Toolkit's createAsyncThunk
API, which will automatically dispatch actions based on async requests and promises.
Also, you should definitely be using our official Redux Toolkit package to write your logic, including configureStore
to replace the store setup code you have there.
As for the specific error you described: I don't immediately see a bug, so it's hard to know what's going on. I'd suggest adding logging in these middleware to see if they're even running, and if the actions you expect are actually reaching them.
Upvotes: 1