Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React map() showing undefined

I have a project where I used redux-saga to make an API call with axios and return the data to the store, which then I mapStateToProps using redux and now I want to map() it and show it on my DOM, but I'm getting "undefined".

Two things keep happening:

  1. either the data doesn't get called in time and the render happens to fast so it says its undefined.
  2. i get map() is not a function or for {blog.id} -- id is undefined.

When I console.log(blogs) i see my array of blogs so I'm not sure what I'm doing wrong. Is it because blogs is an array and so I need to do some kind of for loop to go through the each item and then map it?

Here is my main chunk of code and the console log

import React, {Component} from 'react';
import {connect} from 'react-redux'
import {loadBlogs} from '../../store/actions/blogActions'

class Bloglist extends Component {
    componentDidMount() {
        this.props.loadBlogs();
    }

    render() {
        const {blogs} = this.props
        console.log(blogs)
        return (
            <div>
                <h1>{blogs.map(blog => (
                    <span>{blog.id}</span>
                ))}</h1>
            </div>
        )
    }
}

const mapStateToProps = blogs => ({
    blogs
})
const mapDispatchToProps = dispatch => ({
    loadBlogs: () => dispatch(loadBlogs()),
})

export default connect(mapStateToProps, mapDispatchToProps)(Bloglist)

here is a console log example and an error:

Uncaught TypeError: blogs.map is not a function

this is when I just comment out the map() lines and just return a "hello", this console.log is showing me that the data is coming back

Bloglist.js:14 (3) [{…}, {…}, {…}]

Please let me know if you want any more samples or info. It's really important to get this done so any help would be appreciated! Thanks!

like image 751
josephT Avatar asked Jul 22 '20 02:07

josephT


People also ask

Why is my map undefined?

The "cannot read property 'map' of undefined" error occurs when we call the map() method on an undefined value, most often when the map method is called before the data from an API request has arrived. To solve the error, initialize the value you're mapping over to an empty array.

How do I fix undefined In react JS?

The "cannot set property 'props' of undefined" error occurs when we add an extra set of parenthesis when declaring a class component in React. js. To solve the error, remove the parenthesis after Component in your class declaration, e.g. class App extends Component {} . Here is an example of how the error occurs.

How do you fix Cannot read property of undefined In react?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

How do I read a map in react JS?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.


3 Answers

There can be 2 issues.

  1. Please cross check the type of blogs, it should be array as map method works only on array.

  2. You have to check for array's length before mapping it. As map method doesn't works on empty array.
    Try this code --

     <div>
         <h1>{blogs && blogs.length > 0 ? blogs.map(blog => (
             <span>{blog.id}</span>
         )) : null}</h1>
     </div>
    
like image 172
Ramanpreet Singh Avatar answered Oct 13 '22 02:10

Ramanpreet Singh


At the beginning, your blogs is not an Array. You should to update your reducer initialState, set blocks to be an empty array as default, just like

in reducer.js

const initialState = {
  blogs: [],
};

export default (state = initialState, action) => {
  switch(action) {
    case....

    default:
      return { ...state };
  } 
}

Or, you also should check the blogs before rendering.

Array.isArray(blogs) && blogs.map(item => (
  <div>
    {// item details goes here}
  </div>
))
like image 37
Chuong Tran Avatar answered Oct 13 '22 01:10

Chuong Tran


use ? to handle this error. mostly probably the error is coming from the saga. you have to provide the code better suggest a solution.

 <div>
                <h1>{blogs?.map(blog => (
                    <span>{blog.id}</span>
                ))}</h1>
            </div>
like image 1
prisar Avatar answered Oct 13 '22 02:10

prisar