bier hier
bier hier

Reputation: 22520

Why isn't my state correctly mapped to props in Redux?

I created this component:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export class Todos extends Component {
  render() {
    //todo remove
    console.log('testing this.props.todos', this.props.todos);

    //todo remove
    debugger;

    return (
      <div>hello from todos</div>
    );
  }
}

const mapStateToProps = function (store) {
  return {
      todos: store.todos
  }
}

export default connect(mapStateToProps)(Todos)

I am using Redux and this is the reducer:

const initialState = {
  todos: [
    {
      name:'first todo'
    }
  ]
}

const Todos = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      var newState = Object.assign({}, state, {todos: [...state.todos, action.data]});
      return newState;
    default:
      //todo remove
      debugger;
      return state;
  }
}

export default Todos;

For some reason the this.props.todos is undefined and my state is not mapped to my props correctly. How can I hook up the Redux store to my component?

Upvotes: 1

Views: 46

Answers (1)

Andrew Li
Andrew Li

Reputation: 57934

The problem is that you're not passing the store correctly down to your components! If you want to use connect to connect your component to the global state, you have to use the <Provider> component provided by react-redux. So, first you create your store with createStore as you've done, then pass it into the provider:

import store from './store.js';
import { Provider } from 'react-redux'; 

const App = () => (
  <Provider store={store}>
    <Todos />
  </Provider>
);

ReactDOM.render(
  <div className="container">
    <App />
  </div>
, document.getElementById('root'));

Notice how the <Provider> is used to provide the store and make it available for your connect calls. Also, <Todos> shouldn't take any props. Also, your import:

import { Todos } from './components/todos.jsx';

Is wrong. Your todos.jsx, you're exporting the connected component like this, as the default export:

export default connect(mapStateToProps)(Todos)

So you have to import the default instead:

import Todos from './components/todos.jsx';

Upvotes: 1

Related Questions