Blog>
Snippets

Migrating from redux-observable to Redux v5.0.0

Explain and code an example to show how to migrate from redux-observable to be compatible with middleware changes in Redux v5.0.0.
import { createStore, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { rootEpic } from './epics';
import rootReducer from './reducers';

// Create the epic middleware with the root epic
const epicMiddleware = createEpicMiddleware();

// Create the Redux store, applying the epic middleware
const store = createStore(
  rootReducer,
  applyMiddleware(epicMiddleware)
);

// Run the middleware with the root epic
epicMiddleware.run(rootEpic);

export default store;
Before Redux v5.0.0, this is how you would typically set up your redux-observable middleware in conjunction with the Redux store.
import { configureStore } from '@reduxjs/toolkit';
import { createEpicMiddleware } from 'redux-observable';
import { rootEpic } from './epics';
import rootReducer from './reducers';

// Create the epic middleware with the root epic
const epicMiddleware = createEpicMiddleware();

// Use Redux Toolkit's configureStore instead of createStore
const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(epicMiddleware)
});

// Run the middleware with the root epic
epicMiddleware.run(rootEpic);

export default store;
In Redux v5.0.0 and onwards, the Redux Toolkit's `configureStore` is now the recommended way to set up your store. This code snippet shows how to integrate redux-observable middleware with Redux Toolkit.
import { createSlice } from '@reduxjs/toolkit';

// Example reducer created with createSlice from Redux Toolkit
export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      state.value += 1;
    }
  }
});

export const { incremented } = counterSlice.actions;

export default counterSlice.reducer;
This piece showcases how you would use Redux Toolkit's `createSlice` to define reducers and actions in a way that is compatible with Redux Toolkit's store configuration.