'How can I link certain actions between 2 Redux stores?

I've got a situation whereby I wish to "link" a portion 2 Redux stores together (I know this is unusual), but I can't work out how to filter the actions appropriately.

I have a re-usable component, that has lots of complex state within it and therefore it has a Redux store to manage this. As this is within a library, rather than an application, I can't use the old rule of "single source of truth" as that would break the encapsulation model.

enter image description here

The way I setup my store is as follows, which correctly partitions parts of the store.

const createStore = () => {
    const reducer = combineReducers({
        a: aReducer,
        b: bReducer,
        c: cReducer,
    });

    const composeEnhancers = composeWithDevTools({});
    const store = create(reducer, composeEnhancers(applyMiddleware(ReduxThunk)));

    return store;
};

I then have a bunch of actions, for example here's one which operates on the a part of the store and the b part of the store:

const foo = (payload) => ({
    type: "A.FOO",
    payload,
});

const bar = (payload) => ({
    type: "B.BAR",
    payload,
});

I essentially wish to link two store instances together, so that any operation that happens on a in store1, also happens in store2. I have a list of known types that are available, but I'm not sure how I access them.

I can do this in a primitive way which copies ALL operations:

const [store1, setStore1] = useState();
const [store2, setStore2] = useState();

useEffect(() => {
    if (store1 && store2) {
        const store1_dispatch = store1.dispatch;
        const store2_dispatch = store2.dispatch;

        const dispatch = (...args) => {
            store1_dispatch(...args);
            store2_dispatch(...args);
        };

        store1.dispatch = dispatch;
        store2.dispatch = dispatch;
    }
}, [store1, store2]);

return (
    <>
        <ComponentA onStoreCreated={setStore1} />
        <ComponentB onStoreCreated={setStore2} />
    </>
);

But this breaks various things. Can anyone see a way I can achieve this just copying all actions that operate on a or have an action type that starts with A.*?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source