Search code examples
reactjsreduxredux-persistredux-middleware

How to use redux-persist with custom middleware


Using redux-persist 5.10.0.

It's working perfectly after configuring it using the official documentation:

// configureStore.js
// all imports here

const persistConfig = {
    key: 'root',
    storage,
    whitelist: ['auth']
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export default function configureStore() {
    const store = createStore(
        persistedReducer,
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
        applyMiddleware(axiosMiddleware),
        applyMiddleware(thunk)
    );

    const persistor = persistStore(store);

    return { store, persistor };
}

and:

// index.js
// All imports here

const { store, persistor } = configureStore();

ReactDOM.render(
    <Provider store={ store }>
        <PersistGate loading={null} persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>,
    document.getElementById('root')
);

As you can notice from my configureStore.js file, I have a custom middleware for axios. I'm using JWT for authentication. This middleware will be checking for an action constant named RECEIVE_LOGIN so it can assign the returned token to the default header of my axios instance:

// axiosConfig.js
// imports here
export const axiosMiddleware = ({ dispatch, getState }) => next => action => {
    if (action.type === 'RECEIVE_LOGIN') {
        axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${action.data.token}`;
    }

    return next(action);
}

But because of redux-persist, I cannot get my custom type - RECEIVE_LOGIN - from action.type, I'm getting persist/PERSIST and then persist/REHYDRATE instead. I cannot even find my custom type in action.

I looked it up but couldn't find any example with a custom middleware.

So my question is, how do I use redux-persist alongside my custom middleware?


Solution

  • As a first issue, your store configuration process is wrong. You're calling applyMiddleware more than once. Per the Redux FAQ, calling applyMiddleware multiple times sets up multiple middleware chains, which won't work correctly.

    Change it to be applyMiddleware(axiosMiddleware, thunk), and then see what happens.