carlesba
carlesba

Reputation: 3156

Could we compose different Redux applications to create a bigger one?

I was building a redux application but the scope has changed so now I have to move my app inside another one that it's a redux application as well.

This looks something like:

<MainApp >
  <components />
  <MyApp props={myAppProps} />
</MainApp>

The main problem I found is how to deal with property changes with myApp's store.

So my doubts are:

Upvotes: 2

Views: 129

Answers (3)

webdeb
webdeb

Reputation: 13211

Another solution would be to have a subapp with its own <Provider />

Example:

let store1 = createStore(reducers);
let store2 = createStore(otherReducers);


const RootApp = () => (
  <Provider store={store1}>
    <MainApp />
  </Provider>
)
const MainApp = () => (
  <div>
    <SomeMainAppComponent /> {/* This will receive store1 as context */}

    <Provider store={store2}>
      <EditorApp /> {/* This will receive store2 as context */}
    </Provider>
  </div>
)

Upvotes: 0

webdeb
webdeb

Reputation: 13211

What is actually a Redux App in your opinion?

Redux is just a data management solution for your application:

If you have a two sets of reducers created with combineReducers()

rootReducerForApp = combineReducers({reducer1, reducer2, reducer3});
rootReducerForSomeThingElse = combineReducers({r1, r2, ...});

you could combine those and have a one reducer for your app

combindedRootReducer = combineReducers({
  rootReducerForApp,
  rootReducerForSomeThingElse
})

then create your single Store with

let store = createStore(combinedRootReducer)

Now you can use all the actions you need for both of your semantically separated app-parts from the same place

Upvotes: 1

carlesba
carlesba

Reputation: 3156

Here comes a possible solution. Let's say we have an application that uses an Editor. Both are different apps but the MainApp can pass the file to edit to the Editor. The components will look like this:

<MainApp>
  <Editor
     content={fileContent}
     author={fileAuthor}
     onSubmitFile={(f) => updateFile(f)}
   />
</MainApp>

So MainApp and Editor will have different reducers, stores and actions.

The problem is how to handle Editor's store changes so everything. The way to solve it could be on React's lifecycle. We could create the store when Editor gets mounted and update parts of their store based on the new props.

Something like:

const Editor = React.createClass({
  componentWillMount() {
    const initialData = {...this.props} // pick whatever data we need from props
    this.store = createStore(initialData) // create initial Store
  },
  componentWillReceiveProps (nextProps) {
    const {content, author} = nextProps
    this.store.dispatch(setAuthor(author))
    this.store.dispatch(setContent(content))
  },
  render () {
    return (
      <Provider store={store}>
        <EditorContainers />
      </Provider>
    )
  }
})

Upvotes: 1

Related Questions