Skip to content

Instantly share code, notes, and snippets.

@pixeldrew
Last active July 15, 2016 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixeldrew/b5221a409e5ef743534aa5c658429d25 to your computer and use it in GitHub Desktop.
Save pixeldrew/b5221a409e5ef743534aa5c658429d25 to your computer and use it in GitHub Desktop.
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import React from 'react';
import ReactDOM from 'react-dom';
import {rootReducer, middleware} from 'some-other-module';
const initialData = {'foo': 'Foo', 'bar': 'Bar'}; // perhaps loaded by the server and embedded in the html ie..: const initialData = <? echo $json ?>
const Store = createStore(rootReducer, initialData, middleware);
(async () => {
try {
const response = await fetch('some-ajax-foo-bar');
const data = await response.json();
const x = ReactDOM.render(
<Provider store={Store}>
<RootComponent initialData={data} />
</Provider> , document.getElementById('main'));
} catch (e) {
// let the user know the load failed...
} })();
import React from 'React';
import {connect} from 'react-redux';
import {populateStore} from 'actions'; // simple action
// (state, props) => ({})
// state is the redux store
// props is provided to the HigherOrderComponent on line 16 of loadDefaultState.js
const mapStateToProps = (state, {initialData}}) => ({
populateStore,
initialData,
foo: state.foo,
bar: state.bar
});
export class RootComponent extends React.Component {
componentWillMount() {
this.props.populateStore(this.props.initialData);
}
render() {
return (<div>I have lots of {foo} and lots of {bar}</div>);
}
}
// connect returns a higher order component that listens for all of the redux store changes
// and renders you a component with props that are values from the store.
export default connect(mapStateToProps, {populateStore})(RootComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment