Mauricio Soares
Mauricio Soares

Reputation: 3640

Is it possible to merge created stores in redux?

So, my idea is to enhance an already created store with my own store...

A pseudo code would be something like this:

const store = createStore(reducer);
const myStore = createStore(reducer);

enhanceStore(store, myStore);

The purpose of this is that I'm creating a library that uses redux under the hood, today I'm configuring my own library store... But I wan't to be able to check if the user is already using redux, in that case I want to merge my store with his.

It's not mandatory to merge 2 stores, perhaps I can enhance the already created store with a new reducer...

Thanks!

Upvotes: 7

Views: 7276

Answers (3)

Mohammad Jawad Barati
Mohammad Jawad Barati

Reputation: 754

Inspired from @code-jaff's answer. Please note that I assumed that you have your store creation in a central place.

Try this:

  1. Define your common reducers
  2. Create your store by calling configureStore
  3. define a function called injectReducer and there try to replace the reducers with the new ones and also the common ones. We are gonna utilise combineReducers to do that.
  4. Use the injectReducer utility function in the pages/_app.tsx or app/layout.tsx if you have a nextjs app. or in your App.tsx if you're using a tool like vite/create-react-app. The main point is to use it in the most root level page to just add the extra reducer once to the redux store.

Example:

import {combineReducers, configureStore} from '@reduxjs/toolkit';

const commonReducers = { user: userReducer };
export const store = configureStore({
  reducer: commonReducer,
  // ...
});
// export whatever you like, things like useTypedSelector, etc
export function injectReducer<T>(key: string, reducer: T) {
  store.replaceReducer(combineReducers({
    ...commonReducers,
    [key]: reducer
  }))
};

Upvotes: 0

code-jaff
code-jaff

Reputation: 9330

I hope you're looking for store.replaceReducer()

It is an advanced API. You might need this if your app implements code splitting, and you want to load some of the reducers dynamically.

Upvotes: 5

xiaofan2406
xiaofan2406

Reputation: 3310

This may not be what you are after, but you can export the reducer from the myStore, and combine it with the store's reducer.

combineReducers({
   ...
   myStoreApp: myStoreReducer
)}

If myStore has other important operations like complex initialization, you would have to manually merge those operations together with store's initialization. Just note that the myStore state tree now lives under myStoreApp key

Upvotes: 2

Related Questions