React js: this.state.map is not a function

this.state.data.map is not a function reactjs
map is not a function react redux
×typeerror: this.state is not a function
map is not a function react hooks
this props cards map is not a function
typeerror enumoptions map is not a function
uncaught typeerror is not a function react
undefined is not a function near map

I try solve my problem and can't handle that. I created API using Express JS and I want to display(map) my state array. In componentDidMount() I update listOfUsers[] and console.log return proper data. When I want map my array in render() it return some errors:

Uncaught (in promise) TypeError: this.state.listOfUsers.map is not a function

Uncaught TypeError: this.state.listOfUsers.map is not a function

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

import React, { Component } from 'react';
import axios from 'axios';

class MeetingItem extends Component {
  state = {
    meetings: [],
    listOfUsers: []
  }

  componentDidMount() {
    //get meeting info
    axios.get(`http://localhost:3000/meetings/`+ this.props.match.params.id)
      .then(res => {
        const meetings = res.data;
        this.setState({ meetings });
        //console.log(res.data);
      });

    axios.get(`http://localhost:3000/takePart/`)
      .then(res => {
        for(var i = 0; i < res.data.length; i++){

          //for current meeting
          if(res.data[i]['meetingId'] == this.props.match.params.id){

            //set listOfUsers
            axios.get(`http://localhost:3000/users/`+ res.data[i]['userId'])
              .then(res => {
                const user = res.data;
                this.setState({ 
                  listOfUsers : user
                });

                //in that place data is return 
                console.log(this.state.listOfUsers);
              });
          }
        }
      });
  }

  takePart = () => {
    console.log("take");

    const takePart = {
      meetingId: this.props.match.params.id,
      userId: sessionStorage.getItem('userId'),
    };

    //x-www-form 
    let formBody = [];
    for (let property in takePart) {
        let encodedKey = encodeURIComponent(property);
        let encodedValue = encodeURIComponent(takePart[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    axios.post(`http://localhost:8000/takePart`, formBody, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
      .then(res => {
        console.log(res);
        console.log(res.data);

        //if successfully added a meeting then display alert
        if(res.status == "200"){
            alert("Thank you. See you later.");
        }else{
            alert("Sorry we can't handle that. Please repeat for a while.");
        }
    })
  }


  render() {
    var users = this.state.listOfUsers.map(user => {
      return (
        <p>{user.firstName}</p>
      )
    });

    return (
      <div className="MeetingItem">
        <h1>{/*this.props.match.params.id*/}</h1>
        <p>Title: {this.state.meetings['title']}</p>
        <p>Description: {this.state.meetings['description']}</p>
        <p>Author: {this.state.meetings['author']}</p>
        <p>lattitude: {this.state.meetings['lattitude']}</p>
        <p>longitude: {this.state.meetings['longitude']}</p>
        <p>date: {this.state.meetings['date']}</p>
        <p>time: {this.state.meetings['time']}</p>

        <p>{users}</p>

        <div className="btn btn-default" onClick={this.takePart}>Take part</div> 
      </div>
    );
  }
}

export default MeetingItem;

Any advice?

The API returns list of users should be an array.

To handle this error you can just put a check before map that this.state.listOfUsers is an array.

i.e.

var users = Array.isArray(this.state.listOfUsers) && this.state.listOfUsers.map(user => {
  return (
    <p>{user.firstName}</p>
  )
});

and also make sure that API axios.get('http://localhost:3000/users/'+ res.data[i]['userId']) returned the users list is an array for the expected result.

React JS, The .map function is only available on array. It looks like data isn't in the format you are expecting it to be (it is {} but you are expecting []). this.setState({data: data​});. The most concise screencasts for the working developer, updated daily. There's no shortage of content at Laracasts. In fact, you could watch nonstop for days upon days, and still not see everything!

Since it is not an array you can use something like this:

let myState = Object.entries(this.state);

or Object.values();

This will allow you to iterate over each one of those. With Object.entries for example you can loop over each key, value.

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

React js: this.state.map is not a function, map is not a function. Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method. If you choose not to assign an explicit key to list items then React will default to using indexes as keys. Here is an in-depth explanation about why keys are necessary if you’re interested in learning more. Extracting Components with Keys . Keys only make sense in the context of the surrounding array.

basically, error says listOfUsers is not an array (since it doesn't have map method). It seems, you have an object in your response instead of array:

axios.get(`http://localhost:3000/users/`+ res.data[i]['userId'])
          .then(res => {
            const user = res.data;
            this.setState({ 
              listOfUsers : user
            });

TypeError: items.map is not a function React · Issue #3388 · reduxjs , Component { constructor(props) { super(props); this.state = { items: {}, isLoaded: ..​. TypeError: items.map is not a function React #3388. Closed Children.map .​https://reactjs.org/docs/react-api.html#reactchildrenmap  Rendering an Array of Data with map() and JSX. There's one more thing we're going to cover before you know enough React basics to be able to move on to a real project, and that's how to loop over an array to render its contents.

Inside your render() function, change from:

var users = this.state.listOfUsers.map(user => {
 return (
    <p>{user.firstName}</p>
 )
});

To:

var users = [];
if (this.state.listOfUsers) {
    user = this.state.listOfUsers.map(user => {
       return (
           <p>{user.firstName}</p>
       )
    });
}
The reason

Exception thrown is because when render() is called the first time when the after componentDidMount() hook, this.state.listOfUsers is still undefined. You need to set users = [] empty array by default and only call map() function on the array when it's become an array - after axios promise call resolved. As soon as the axios call is resolved, it well set this.state.listOfUsers to be an array and render() is called again to update UI.

Reactjs (this.state.data.map) is not a function, Reactjs (this.state.data.map) is not a function. Posted 2 years ago by mlazuardy. well i follow the tutorial from internet to list and key data with  State Management in a React js Component Before we can get into the details about creating a state within our component, it's important to note that state can only be created in a class component . The reason for this is the fact that our state will be housed in a class constructor.

TypeError: .map is not a function (React js) - JavaScript, TypeError: .map is not a function (React js) </div> ); } } export default connect( state => ({ catalogs: state.catalogs, selectedProduct: state. React will only call this function after a click. Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders. As a next step, we want the Square component to “remember” that it got clicked, and fill it with an “X” mark.

'TypeError: this.state.news.map is not a function' in ReactJS, First step is to understand what the error means. I assume you are trying to use the map() function from an array type. This error is telling you news does not  Debouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called. This can be useful when you have to perform some expensive calculation in response to an event that might dispatch rapidly (eg scroll or keyboard events).

React, tl:dr Check the function in your constructor that implements the adding of an item to an array, refer Tagged with react, javascript. First step is to understand what the error means. I assume you are trying to use the map() function from an array type. This error is telling you news does not

Comments
  • Check the res.data. I am sure that it is not an array. The map is one of Array's methods, so the error occurs.