score:5

Accepted answer

your redux store's courses might be undefined at the start and hence this.props.courses becomes undefined. trying to access .map of undefined will give you the error you mentioned above. there are a few ways to fix this:

approach 1 (recommended): set the initial value of the state.courses to empty array [] in your the reducer. refer to the documentation on reducers to see how to set an initial state: http://redux.js.org/docs/basics/reducers.html.

approach 2: set a default value for props.courses in mapstatetoprops.

function mapstatetoprops(state,ownprops){
  return {
    courses: state.courses || []
  };
}

approach 3: check that this.props.courses is not undefined or null before rendering it:

courserow() {
  if (!this.props.courses) {
    return null;
  }

  return this.props.courses.map((course)=>{
    return(
      <div key={course.id}>{course.title}</div>
    );
  });
}

score:2

your mapstatetoprops is returning a reducer instead of actual props that you can use right away. it should probably look like this:

function mapstatetoprops(state,ownprops){
     return{
        ...state.courses
     };
}

score:3

in your reducer where are you updating courses?? i can only see users from the code you posted.

 const initialstate = {
        courses : [],
 }



export default function coursereducer(state =initialstate,action){
    switch(action.type){
       //create a course or update it , else value is 
       //undefined and your map would throw error.
       case 'create_courses':
         return object.assign({},state,{
                 courses : action.user}
          );
         default:
          return state;
      }
}

also in your render method you need to check if this value is filled then only run map.

 <h3>{this.props.courses.length > 1 ? this.courserow() : null}</h3>

score:3

after modifying the code with the help of both @harkirat saluja and @yang shun. i manages to fix the issue which was initializing courses so i changed my reducer as below

state = [] did the trick!

 export default function coursereducer(state = [],action){
        switch (action.type) {
          case 'create_course':
                return [...state,object.assign({},action.course)];
           default:
            return state;

        }
    }

Related Query

More Query from same tag