Skip to content

Set up Application Store

JP Barbosa edited this page Feb 10, 2017 · 1 revision

Now that we already have our reducers up and working and our state fleshed out, we need to integrate it into our React app. We will do it through the react-redux library we have installed in the previous step.

Setting up the Provider

In order for our application to see the global state, we need to wrap it in a higher-order component called Provider that comes with the react-redux library. Doing that allows us to wire our app components to Redux and have access to the state through props.

nano src/index.js

The default index.js provided by the Create React App boilerplate looks like this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

We're going to wrap that App component with the Provider component mentioned above.

Provider takes a prop called store that's going to be the source of our state. In order to create a store, the redux library furnishes us with a createStore function that takes another function as an argument, a reducer. Since we have already wired a reducer up, that's what we're going to pass to createStore to, well, create our store.

The final index.js file will look like this:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './reducers';
import App from './App';
import './index.css';

const store = createStore(reducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Now our app has access to the Redux global state. However, if we reload the page, we will notice that pretty much nothing has changed on the outside. That's because we haven't created any components that interact with the application state. However, we can still see the initial state by calling store.getState() inside our index.js.

...
const store = createStore(reducer);
console.log(store.getState());

ReactDOM.render(
...

Open http://localhost:3000 and check your console. You'll see an object with the exact same structure that we have defined at the beginning of the guide. That's because the function returned by combineReducers returns an object like the one we supplied to it, and the values of the keys are the pieces of state returned by each of the reducers we have created separately.

Commit the changes and head to the next step.

git add .
git commit -m "Create application store and wire it up to the app"

Next step: Set up Contact List

Clone this wiki locally