Alex C
Alex C

Reputation: 1335

How to set initial state in top level react component with redux?

I want something like this:

MyMainComponent = React.createClass({
  getInitialState()=>{
    let state = store.getState();
    return Object.assign([], state, initialDataset: this.props.initialDataset)
  }
})

and somewhere else in the code:

let store = createStore(reducers, {
  foo: "default"
  initialDataset: []
})

export const MyApp = ({ initialDataset }) => (
  <Provider store={store}>
    <MyMainComponent initialDataset={initialDataset}  />
  </Provider>
)

I haven't found any examples that come close to this yet. I am not sure it's even possible.

Edit: I wanna add that MyApp is called in a ruby helper with initialDataset instanciated server-side.

Upvotes: 0

Views: 836

Answers (1)

VonD
VonD

Reputation: 5155

As azium highlighted, it doesn't seem necessary to duplicate the redux store's state into your top-level component's state.

If your concern is to instantiate the store with the initialDataset client-side, you can add a script tag in your HTML with a global variable :

// assuming you are in a erb template
<script>window.__INITIAL_STATE__ = <%= JSON.generate(initial_dataset) %></script>

Then in your assets, you can use it like so :

let store = createStore(reducers, {
  foo: "default"
  initialDataset: window.__INITIAL_STATE__ || []
});

You can find an example of that in the redux docs : http://redux.js.org/docs/recipes/ServerRendering.html

Hope it helps

Upvotes: 1

Related Questions