Меню

Map is not a function react ошибка

import React, {Component} from 'react';
import './App.css';
import axios from 'axios';

export default class App extends Component {

    constructor() {
        super();
        this.state = {
            weather: []
        };
    }
componentDidMount (){

  this.search();
}
    search = () => {

        axios.get("http://api.openweathermap.org/data/2.5/weather?q=Houston&APPID=f2327cca8f3d665f4c9f73b615b294ed")
        .then(res => {

            this.setState({weather: res.data});

        }).catch(error => {
            console.log('Error from fetching data', error);
        })
    }

    render() {
    console.log(this.state.weather);
    const weathermap = this.state.weather.map( (maps) =>{
      {maps.wind.speed}
});

        return (
            <div className="container">
                <div className="row">
                    <div className="col-md-4 col-md-offset-4">
                        <div className="weather">
                            <div className="current">
                                <div className="info">
                                    <div>&nbsp;</div>
                                    <div className="city">
                                        <small>
                                            <small>CITY:</small>
                                        </small>
                                        {this.state.weather.name}</div>
                                    <div className="temp">67&deg;
                                        <small>F</small>
                                    </div>
                                    <div className="wind">
                                        <small>
                                            <small>WIND:{weathermap}</small>
                                        </small>

                                        </div>
                                    <div>&nbsp;</div>
                                </div>
                                <div className="icon">
                                    <span className="wi-day-sunny"></span>
                                </div>
                            </div>
                            <div className="future">
                                <div className="day">
                                    <h3>Mon</h3>
                                    <p>
                                        <span className="wi-day-cloudy"></span>
                                    </p>
                                </div>
                                <div className="day">
                                    <h3>Tue</h3>
                                    <p>
                                        <span className="wi-showers"></span>
                                    </p>
                                </div>
                                <div className="day">
                                    <h3>Wed</h3>
                                    <p>
                                        <span className="wi-rain"></span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        );
    }
}

I am getting a «this.state.weather.map is not a function» error. I am fetching data from weather api. I got the name from api displayed ok. api call it self is ok is success too.
here how the api looks like in console enter image description here

here is the code

asked Mar 24, 2017 at 1:10

jsPlayer's user avatar

3

You are instantiating the app by saying this.state = { weather: []};. However, When you say this.setState({weather: res.data}), you are overriding the this.state.weather to a JavaScript object rather than array, thus the .map is not available anymore.

You can achieve what you’re trying to do by simply const weathermap = this.state.weather.wind.speed

answered Mar 24, 2017 at 1:18

Suthan Bala's user avatar

Suthan BalaSuthan Bala

3,1595 gold badges33 silver badges58 bronze badges

1

this.state.weather is a javascript object so .map is not available you can use

Object.Keys(YourObject).map() 

answered Mar 28, 2017 at 11:23

Amir Tahani's user avatar

Amir TahaniAmir Tahani

6685 silver badges13 bronze badges

You should do conditional check and then do .map like

.map with return syntax

const { weather } = this.state;
const weathermap = weather && weather.map(maps => {
      return <span>{maps.wind && maps.wind.speed}</span>
});

.map without return syntax

const { weather } = this.state;
const weathermap = weather && weather.map(maps => (
     <span>{maps.wind && maps.wind.speed}</span>
));

answered Sep 28, 2018 at 12:13

Hemadri Dasari's user avatar

Hemadri DasariHemadri Dasari

31.4k34 gold badges115 silver badges157 bronze badges

map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables which are not array.

Consider this example –

var superHero = {
  'hero' : [
              'Captain America',
              'Ironman',
              'Hulk',
              'Thor',
              'Scarlet Witch',
           ],
}

const superHeroList = () => {
  return (
     <>
       {
         superHero.map(hero => {
           return (<p>{hero}</p>)
         })
       }
     </>
  )
}

The above code will create error in map function. Because superHero is not an array. Else it’s an object which has a property, hero, which is an array of super heroes.

To correctly call map function, we need to change our code and instead of calling it as superHero.map, we need to call it as superHero.hero.map.

var superHero = {
  'hero' : [
              'Captain America',
              'Ironman',
              'Hulk',
              'Thor',
              'Scarlet Witch',
           ],
}

const superHeroList = () => {
  return (
     <>
       {
         superHero.hero.map(hero => {
           return (<p>{hero}</p>)
         })
       }
     </>
  )
}

    Tweet this to help others

Open Live Demo

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • javascript error,
  • javascript short,
  • react js short,
  • reactjs error

TypeError: .map is not a function occurs when we call map() function on object which is not an array. map() function can be only called on array.

Let’s see with help of simple example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var numObj =

{

  ‘Numbers’ : [

              1,

             2,

             3,

           ],

  ‘NumberTexts’:[‘ONE’,

             ‘TWO’,

             ‘THREE’,

             ],

}

const result = numObj.map(num => {

  return num *2;

});

console.log(result);

You will get following error when you execute the program:

const result = numObj.map(element => {

                      ^

TypeError: numObj.map is not a function

    at Object.<anonymous> (HelloWorld.js:18:23)

    at Module._compile (internal/modules/cjs/loader.js:959:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)

    at Module.load (internal/modules/cjs/loader.js:815:32)

    at Function.Module._load (internal/modules/cjs/loader.js:727:14)

    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)

    at internal/main/run_main_module.js:17:11

We got this error because numObj is not an array, it is an object.

To correctly call map() function, we need to use numObj.Numbers. map() function will multiply elements of Numbers array by 2.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var numObj =

{

  ‘Numbers’ : [

              1,

             2,

             3,

           ],

  ‘NumberTexts’:[‘ONE’,

             ‘TWO’,

             ‘THREE’,

             ],

}

const result = numObj.Numbers.map(num => {

  return num *2;

});

console.log(result);

Output:

You can avoid the error by using Array.isArray() method to check if value is an array. If it is not an array, then we can return empty value.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var numObj =

{

  ‘Numbers’ : [

              1,

             2,

             3,

           ],

  ‘NumberTexts’:[‘ONE’,

             ‘TWO’,

             ‘THREE’,

             ],

}

const result = Array.isArray(numObj)?numObj.map(element => {

  return element *2;

}):[];

console.log(result);

Output:

As you can see numObj is not an array, so result is [].

If you have array like objects, then first convert them to array using Array.from() method and then call map method on it.

const countries = new Set([«India», «China», «Bhutan»]);

const result = Array.from(countries).map(country => country.toUpperCase());

console.log(result);

As you can see, we have converted set to Array using Array.from() method then called .map() function to convert country names to uppercase.

If you are getting this error while dealing with JSON, you need to make sure that you are calling map() function only on arrays. It may be good idea to log the JSON on console and see if you are calling map() on correct value.

map is not a function in react

If you are getting issue in react, you need to first check if calling object is array or not using Array.isArray() method.

Array.isArray(obj):/*call map function with logic*/:/*[]*/

If it is not an array, then you may need to convert your object to array and call .map() method on it.

That’s all about how to resolve .map is not a function in Javascript.

@Belssem

import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import LoginForm from './LoginForm';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: {},
      isLoaded: false,
    }
  }
  componentDidMount() {
    fetch(' http://127.0.0.1:8000/api/roles')
      .then(res => {return res.json();})
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json,    })
      });
  }
  render() {

  const { isLoaded, items } = this.state;
    if (!isLoaded) {
      return <div>Loading...</div>
    }
    else {
      return (
        <div >
         <ul>
           {items.map( item => 
             <li key={item.id}>{item.name}</li>
           )}
         </ul>
      </div>
      )
    }
  }
}
export default App

I got this problem when i try to fetch data from an api to react . any help plz?

@FireyFly

This code doesn’t appear to use Redux at all. I would suggest StackOverflow or a React tutorial for general React questions/debugging like this.

@piotrekdonicz

You can’t iterate over an object, as you set items: {}. Object.map() will throw you an error ‘map is not a function’

@Belssem

import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import LoginForm from './LoginForm';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
    }
  }
  componentDidMount() {
    fetch(' http://127.0.0.1:8000/api/roles')
      .then(res =>   res.json())
      .then(json => {
        console.log(this.state.items)
        this.setState({
          isLoaded: true,
          items: json
        });
  })}
  render() {
    var { items = [] } = this.props;
    var { isLoaded } = this.state;
    if (!isLoaded) {
      return <div>Loading...</div>
    }
    else {
      return (
        <div >
         <ul>
           {items.map( item => (
             <li key={item.id}> Name : {item.name}</li>
           ))}
         </ul>
      </div>
      )
    }
  }
}
export default App

Now I changed it to items: [] but i got any resuls : the error was gone but i didn’t see anything in the screen

@timdorr

This has nothing to do with Redux.

@Luoxue-xu

import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import LoginForm from './LoginForm';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: {},
      isLoaded: false,
    }
  }
  componentDidMount() {
    fetch(' http://127.0.0.1:8000/api/roles')
      .then(res => {return res.json();})
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json,    })
      });
  }
  render() {

  const { isLoaded, items } = this.state;
    if (!isLoaded) {
      return <div>Loading...</div>
    }
    else {
      return (
        <div >
         <ul>
           {items.map( item => 
             <li key={item.id}>{item.name}</li>
           )}
         </ul>
      </div>
      )
    }
  }
}
export default App

I got this problem when i try to fetch data from an api to react . any help plz?

you can try React.Children.map .https://reactjs.org/docs/react-api.html#reactchildrenmap

@reduxjs
reduxjs

locked as resolved and limited conversation to collaborators

Apr 1, 2019

When we fetch data in our React front-end app from API, sometimes we fetch some errors. In this article, we just discuss one of them which is Uncaught TypeError: this.props.data.map is not a function. Before discuss about this error we discuss about what is .map() and how it works. The .map() is a javascript array function. It’s executed with only array data and create a new array with some modification if needed. Now is the time to move eyes towards error. First we will create the same error and then we will fix it with example. 

App.js

  import React, { Component } from 'react';
  import TodoList from "./TodoList";

  class App extends Component {
    constructor() {
      super();
      this.state = ({
        todos: ""
      });
    }

    componentDidMount() {
      this.setState({
        todos: [
          { id: 1, title: "Todo 1" },
          { id: 2, title: "Todo 2" },
          { id: 3, title: "Todo 3" },
          { id: 4, title: "Todo 4" },
          { id: 5, title: "Todo 5" }
        ]
      });
    }

    render() {
      return (
        <div>
          <TodoList data={ this.state.todos }/>
        </div>
      );
    }
  }

  export default App;

TodoList.js

  import React, { Component } from 'react';

  class TodoList extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      return (
        <ul>
          { this.props.data.map(todo => {
            return (
              <li key={ todo.id }>{ todo.title }</li>
            );
          }) }
        </ul>
      );
    }
  }

  export default TodoList;

Here we have two components. One is App.js which is parent component and another one is TodoList.js which is child component of App.js component. In the App.js component, we have a todos state which initial value is a null string. We update the todos state when the component is rendered. And the todos state passed into the TodoList.js component as props. In the TodoList.js, we have been used .map() function to execute the props data.

Now if we run our project, we will see the error. If I ask you, can you tell me where is the problem? Don’t worry, now I will explain to you where is the problem. We know that .map() function only executed with array data. Now we will try to find out the source of this.props.data which is executed with .map() function. this.props.data comes from parent component which is represent App.js todos state. Now here’s a question. Is Todos an array? After App.js rendered Todos is an array but initially this is a null string. That’s the problem. Just change the Todos initial state as an array and run the project again and see the magic.

App.js

  import React, { Component } from 'react';
  import TodoList from "./TodoList";

  class App extends Component {
    constructor() {
      super();
      this.state = ({
        todos: []   // just update null string to array
      });
    }

    componentDidMount() {
      this.setState({
        todos: [
          { id: 1, title: "Todo 1" },
          { id: 2, title: "Todo 2" },
          { id: 3, title: "Todo 3" },
          { id: 4, title: "Todo 4" },
          { id: 5, title: "Todo 5" }
        ]
      });
    }

    render() {
      return (
        <div>
          <TodoList data={ this.state.todos }/>
        </div>
      );
    }
  }

  export default App;

The JavaScript exception «is not a function» occurs when there was an attempt to call a
value from a function, but the value is not actually a function.

Message

TypeError: "x" is not a function. (V8-based & Firefox & Safari)

Error type

What went wrong?

It attempted to call a value from a function, but the value is not actually a function.
Some code expects you to provide a function, but that didn’t happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method
on does not have this function? For example, JavaScript Objects have no
map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to
provide a function in order to have these methods working properly:

  • When working with Array or TypedArray objects:
    • Array.prototype.every(), Array.prototype.some(),
      Array.prototype.forEach(), Array.prototype.map(),
      Array.prototype.filter(), Array.prototype.reduce(),
      Array.prototype.reduceRight(), Array.prototype.find()
  • When working with Map and Set objects:
    • Map.prototype.forEach() and Set.prototype.forEach()

Examples

A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

const x = document.getElementByID('foo');
// TypeError: document.getElementByID is not a function

The correct function name is getElementById:

const x = document.getElementById('foo');

Function called on the wrong object

For certain methods, you have to provide a (callback) function and it will work on
specific objects only. In this example, Array.prototype.map() is used,
which will work with Array objects only.

const obj = { a: 13, b: 37, c: 42 };

obj.map(function (num) {
  return num * 2;
});

// TypeError: obj.map is not a function

Use an array instead:

const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num * 2;
}); // [2, 8, 18]

Function shares a name with a pre-existing property

Sometimes when making a class, you may have a property and a function with the same
name. Upon calling the function, the compiler thinks that the function ceases to exist.

function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function

Use a different property name instead:

function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; //Using this.dogName instead of .name
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }

Using brackets for multiplication

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// 2 x (3 + 5) is 16

Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

const helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
}

export default helpers;

The correct import usage (App.js):

import helpers from './helpers';

See also

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Map fail gigabyte ошибка
  • Map construction ошибка dxt5