Fivapr
Fivapr

Reputation: 41

mapStateToProps doesn't provide a data from the state

I have this error:

TypeError: Cannot read property 'map' of undefined

And don't know how can this.props.movies be undefined while I have initialState declared as [] and then it must straightly go to render?

So there are files:

Reducer.js

import * as types from "./ActionTypes.js";

const initialState = { movies: [] };

export const reducer = (state = initialState, action) => {
  console.log(state.movies);
  switch (action.type) {
    case types.GET_MOVIES:
      return {
        ...state,
        movies: action.value
      };
    default:
      return state;
  }
};

Movies.js

import React, { Component } from "react";
import { connect } from "react-redux";
import MovieItem from "./MovieItem";

const mapStateToProps = state => ({
  movies: state.movies
});

class Movies extends Component {
  render() {
    let movieItems = this.props.movies.map(movie => {
      return <MovieItem movie={movie} />;
    });
    return <div className="Movies">{movieItems}</div>;
  }
}

export default connect(mapStateToProps, null)(Movies);

And even if I put if-statement like

if (this.props.movies){
...
}else return 1;

it never rerenders

Upvotes: 3

Views: 410

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104359

It should be:

const mapStateToProps = state => ({
    movies: state.reducer.movies
});

Because your initial state is a object:

initialState = { movies: [] };

And you are using combineReducers like this:

const rootReducer = combineReducers({ reducer: reducer }); 

Now all the initialState of that reducer will be accessible by state.reducer.propertyName.

Note: Instead of using reducer, better to use some intuitive name like moviesReducer. Later in future if you will add more reducers then it will help to identify the the data.

Upvotes: 1

Related Questions