Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Create a Redux Store

    Andy Van SlaarsAndy Van Slaars

    The redux store is the glue that holds this state management structure together. In this lesson we’ll use the redux library to create a store with the createStore function and then refactor our existing code to pass state into the app using the store’s getStore method.

    reactReact
    15 - 16
    reduxRedux
    3 - 4
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 We've created this reducer for our application, but we still need to install Redux and then use the reducer to control our application state. In the terminal, I'm going to use yarn to add Redux by running yarn add redux.

    00:19 Now that Redux that has been installed as a dependency of the project, we're going to create a new file directly in the source, and we're going to call this store.js. In store.js we're going to import a function called createStore from Redux, and we're also going to import our reducer.

    00:43 We'll import reducer, we don't need the curly braces here because that was our default export. That will be from reducer/todo. Now, I'm going to export defaults and I'm going to call createStore, and I'm going to pass createStore my reducer.

    01:05 With our store created, I'm going to open index.js and I'm going to import store from and the path to store. Now, I'm going to get rid of this state object, and I'm going to replace this with a call to store.getState, and then in my app rather than passing in todos as its own property, I'm just going to spread state and I'm going to save this.

    01:44 Then back in the terminal, I'm going to start the application with yarn start, and I'm going to switch back to the browser and we'll see that our application is running, but I'm no longer displaying any todos.

    01:56 The reason for this is that I got rid of those hard-coded todos that were in that initial state, and instead our store is calling a reducer, and a reducer is getting an undefined state on the first run, and it's using this initial state.

    02:09 I can fix this by adding a couple of objects to this todos array. I'm just going to paste in a few todo objects here, and I'm going to save this. When our browser reloads, we'll see that we have todo objects being loaded through our store.

    Discuss

    Discuss