React and Redux: Managing Redux Custom Middleware List
Asked Answered
J

1

11

For my react app, I have built many custom middlewares and passed them in the applyMiddleware(). Because I have so many, the redux store file is looking a little congested. Is it a good practice to pass them all in the applyMiddleware() or import them in a separate file within a function and then pass that function in the applyMiddleware() to keep it clean?

// Redux store
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
  reducers,
  composeEnhancers(
    applyMiddleware(...xMdl, ...yMdl, ...zMdl, ...nAmountsOfMdl),
  )
);
Josiahjosias answered 28/11, 2020 at 22:28 Comment(0)
E
3

I prefer to make groups for reducers using combineReducers. ill share my middleware setup, hope it's helpful for u!

store.config.js :

import rootReducer from '../_reducers'

export const history = createBrowserHistory()

export const store = configureStore();

export default function configureStore(preloadingState) {
  const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  const store = createStore(
    rootReducer(history),
    preloadingState,
    composeEnhancer(
      applyMiddleware(
        routerMiddleware(history),
        thunk,
      ),
    ),
  )

  return store
}

index.js (in reducers folder) :

const rootReducer = (history) => combineReducers({
    router: connectRouter(history),
    single: combineReducers({
        post: postReducer,
        guide: guideReducer,
        course: courseReducer,
        lesson: lessonReducer,
        exercise: exerciseReducer,
    }),
    bank: combineReducers({
        posts: postsReducer,
        guides: guidesReducer,
        courses: coursesReducer,
        lessons: lessonsReducer,
        exercises: exercisesReducer,
    }),
    melodition: playerReducer,
    user: combineReducers({
        profile: profileReducer,
        favorites: favoriteReducer,
    }),
    snackbar: snackbarReducer,
    auth: authReducer,
});

export default rootReducer;

Note: I did this on a large project with connected-react-router, maybe it's not good for every project.

Elconin answered 3/12, 2020 at 9:47 Comment(3)
Thank you. Nice to see what others are doing. Thanks for sharing!Josiahjosias
Also, my get custom api middle is firing but not my delete. How do you approach the custom delete api middleware?Josiahjosias
no problem happy to help u ,can u share ur delete api middleware details ? did u dispatch it ? i have wordpress for handling sever side api, but on application to delete data from redux store an action for making new array of items, example: export const deletePost = (id) => ((dispatch,getState) => {const newPosts = getState().bank.posts.data.filter(post => post.id !== id);dispatch({ type: DELETE_POST, newPosts })})Elconin

© 2022 - 2024 — McMap. All rights reserved.