[javascript] React JS - Uncaught TypeError: this.props.data.map is not a function

I'm working with reactjs and cannot seem to prevent this error when trying to display JSON data (either from file or server):

Uncaught TypeError: this.props.data.map is not a function

I've looked at:

React code throwing “TypeError: this.props.data.map is not a function”

React.js this.props.data.map() is not a function

Neither of these has helped me fix the problem. After my page loads, I can verify that this.data.props is not undefined (and does have a value equivalent to the JSON object - can call with window.foo), so it seems like it isn't loading in time when it is called by ConversationList. How do I make sure that the map method is working on the JSON data and not an undefined variable?

var converter = new Showdown.converter();

var Conversation = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="conversation panel panel-default">
        <div className="panel-heading">
          <h3 className="panel-title">
            {this.props.id}
            {this.props.last_message_snippet}
            {this.props.other_user_id}
          </h3>
        </div>
        <div className="panel-body">
          <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
        </div>
      </div>
    );
  }
});

var ConversationList = React.createClass({
  render: function() {

    window.foo            = this.props.data;
    var conversationNodes = this.props.data.map(function(conversation, index) {

      return (
        <Conversation id={conversation.id} key={index}>
          last_message_snippet={conversation.last_message_snippet}
          other_user_id={conversation.other_user_id}
        </Conversation>
      );
    });

    return (
      <div className="conversationList">
        {conversationNodes}
      </div>
    );
  }
});

var ConversationBox = React.createClass({
  loadConversationsFromServer: function() {
    return $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadConversationsFromServer();
    setInterval(this.loadConversationsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="conversationBox">
        <h1>Conversations</h1>
        <ConversationList data={this.state.data} />
      </div>
    );
  }
});

$(document).on("page:change", function() {
  var $content = $("#content");
  if ($content.length > 0) {
    React.render(
      <ConversationBox url="/conversations.json" pollInterval={20000} />,
      document.getElementById('content')
    );
  }
})

EDIT: adding sample conversations.json

Note - calling this.props.data.conversations also returns an error:

var conversationNodes = this.props.data.conversations.map...

returns the following error:

Uncaught TypeError: Cannot read property 'map' of undefined

Here is conversations.json:

{"user_has_unread_messages":false,"unread_messages_count":0,"conversations":[{"id":18768,"last_message_snippet":"Lorem ipsum","other_user_id":10193}]}

This question is related to javascript ajax json reactjs

The answer is


I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was

const [favoriteFilms, setFavoriteFilms] = useState('');

I changed it to

const [favoriteFilms, setFavoriteFilms] = useState([]);

and the component that uses those values stopped throwing error with .map function.


It happens because the component is rendered before the async data arrived, you should control before to render.

I resolved it in this way:

render() {
    let partners = this.props && this.props.partners.length > 0 ?
        this.props.partners.map(p=>
            <li className = "partners" key={p.id}>
                <img src={p.img} alt={p.name}/> {p.name} </li>
        ) : <span></span>;

    return (
        <div>
            <ul>{partners}</ul>
        </div>
    );
}
  • Map can not resolve when the property is null/undefined, so I did a control first

this.props && this.props.partners.length > 0 ?


If you're using react hooks you have to make sure that data was initialized as an array. Here's is how it must look like:

const[data, setData] = useState([])

You don't need an array to do it.

var ItemNode = this.state.data.map(function(itemData) {
return (
   <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
 );
});

try componentDidMount() lifecycle when fetching data


You need to convert the object into an array to use the map function:

const mad = Object.values(this.props.location.state);

where this.props.location.state is the passed object into another component.


More generally, you can also convert the new data into an array and use something like concat:

var newData = this.state.data.concat([data]);  
this.setState({data: newData})

This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.


As mentioned in the accepted answer, this error is usually caused when the API returns data in a format, say object, instead of in an array.

If no existing answer here cuts it for you, you might want to convert the data you are dealing with into an array with something like:

let madeArr = Object.entries(initialApiResponse)

The resulting madeArr with will be an array of arrays.

This works fine for me whenever I encounter this error.


what worked for me is converting the props.data to an array using data = Array.from(props.data); then I could use the data.map() function


I had a similar error, but I was using Redux for state management.

My Error:

Uncaught TypeError: this.props.user.map is not a function

What Fixed My Error:

I wrapped my response data in an array. Therefore, I can then map through the array. Below is my solution.

const ProfileAction = () => dispatch => {
  dispatch({type: STARTFETCHING})
  AxiosWithAuth()
    .get(`http://localhost:3333/api/users/${id here}`)
    .then((res) => {
        // wrapping res.data in an array like below is what solved the error 
        dispatch({type: FETCHEDPROFILE, payload: [res.data]})
    }) .catch((error) => {
        dispatch({type: FAILDFETCH, error: error})
    })
 }

 export default ProfileAction

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release