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,1795 gold badges34 silver badges59 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

6885 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

32.3k36 gold badges118 silver badges160 bronze badges

Check out the information in this post. You will find the detailed instruction for the TypeError: map() is not a function in React. To avoid this error, you must make sure that you use the map() method on an array value. Let’s learn more about the cause and the most suitable approach to this problem.

Why do we have this error?

First, we have to know what causes you to get the error message: “TypeError: map() is not a function“. Look at the following example, it will throw this error:

export default function App() {
 
const myChild = {name: 'Kai', age: 12};
 
  return (
    <div>
      {myChild.map(item => {
        return <h2>{item}</h2>;
      })}
    </div>
  );
};

Output:

The reason you receive this error message is that you are applying the map() method to a non-array object.

In JavaScript, the map() method creates an array by calling a specific function on each element contained in the parent array. So you cannot arbitrarily call the map() method without knowing the type of that object.

The simplest way to avoid this error is to use the map() method on an object that is an array, like the following example:

export default function App() {
 
  const friends = ['Celina','Nick','James','Tayor','Paul']
 
  return (
   
    <div>
      { friends.map(item => {
          return <h2>{item}</h2>;
        })
      }
 </div>
  );
};

However, if you don’t know whether the value is really an array or not, you can use the Array.isArray() method to check.

export default function App() {
 
  const myChild = {name: 'Kai', age: 12};
 
  return (
   
    <div>
      { Array.isArray(friends)
        ? friends.map(item => {
          return <h2>{item}</h2>;
        })
        : console.log('Object is not an array')
      }
    </div>
  );
}; 

In this example, the ternary operator is used for conditional rendering. In case the value is an array, the map() method will be called. Otherwise, you will get a message: “Object is not an array“.

In another case, you have an array-like object that you try to convert to an array before calling the map method using the Array.from() method.

export default function App(){
  const friends = new Set(['Timmy', 'Carl', 'Jenny']);
 
  return (
    <div>
      {Array.from(friends).map(element => {
        return (
          <div key={item}>
            <h2>{item}</h2>
          </div>
        );
      })}
    </div>
  );
  };

We convert the value to an array before calling the map method. You can apply this approach to NodeList, which is returned when you call the getElementsByClassName method.

In case you work with an object, you will not be able to use the map() method to iterate through all the elements in the array because map() is only usable with array values.

At this point, you can use method Object.keys() to get the array of keys or method Object.values() to get the array of values ​​of that object.

export default function App() {
 
  const myChild = {
    name: 'Kai',
    age: 12,
  };
 
  return (
    <div>
      {/*iterate over an object's array of keys*/}
      {Object.keys(myChild).map((key) => {
        return (
          <div key={key}>
            <h2>
              {key}
            </h2>
          </div>
        );
      })}
 
      <br />
 
      {/*iterate over an object's array of values*/}
      {Object.values(myChild).map((value, idx) => {
        return (
          <div key={idx}>
            <h2>{value}</h2>
          </div>
        );
      })}
    </div>
  );
}

Summary

In conclusion, we have explained to you what causes the TypeError: map() is not a function in React. To avoid the error, you must call the map() method on an array object. Hopefully, the information in this article will help you.

Maybe you are interested:

  • Property does not exist on type ‘never’ in React
  • Module not found: Can’t resolve ‘babel-loader’

My name’s Christopher Gonzalez. I graduated from HUST two years ago, and my major is IT. So I’m here to assist you in learning programming languages. If you have any questions about Python, JavaScript, TypeScript, Node.js, React.js, let’s contact me. I will back you up.

Name of the university: HUST
Major: IT
Programming Languages: Python, JavaScript, TypeScript, Node.js, React.js

When developing a React application, you might have come across an error stating «TypeError: map() is not a function». This error usually occurs when you are attempting to use the map() method on a non-iterable object that is not an array or an instance of an Array.

To understand this error, it is important to understand how map() works.

What is map() in Javascript?

The map() method is an in-built javascript function that creates a new array with the result of a provided call function on every element of a given array.

In short, we can say, it transforms an array of values into a new array of values.

Here is a simple example of using a map() method on an array.

const arr = [1, 2, 3, 4, 5];
const doubleNumbers = arr.map(el => el * 2);
console.log(doubleNumbers); // [2, 4, 6, 8, 10]

In this example, we have called the map method on arr and a new array is created doubleNumbers, with each element of arr being multiplied by 2.

Now with the understanding of map(), let’s see different ways we can fix the error in react application.

Fixing «React map is not a function» Error

The error «TypeError: map() is not a function» occurs when we call the map method on a value that is not an array or an object.

Here, is an example of how this error might occur.

export default function App() {
  const obj = { name: "Jack", country: "USA" };
  return (
    <div className="App">
      {obj.map((el) => {
        return <p>{el}</p>;
      })}
    </div>
  );
}

This will throw us the «TypeError: obj.map is not a function» error in our terminal.

Now here are some of the ways we can do to fix this error.

Using a valid Array

The most simple and easy fix is to call map() method on a valid array. Here is an example.

Example:

export default function App() {
  const arr = ['one', 'two', 'three'];
  return (
    <div className="App">
      {arr.map((el) => {
        return <p>{el}</p>;
      })}
    </div>
  );
}

Result:

Using Object.values() or Object.entries() method

Now if you have an object on which you want to use the map() method, then first we have to convert it to an array.

We can use Object.values() and Object.entries() to convert the object into an array before using the map() method on it.

Example:

export default function App() {
  const obj = { name: "Jack", country: "USA" };
  const dataArr = Object.values(obj);

  return (
    <div className="App">
      {dataArr.map((el) => {
        return <p>{el}</p>;
      })}
    </div>
  );
}

Result:

The Object.values() returns only the values from an object in an array. If you want both key — value from the object, you can use Object.entries() method.

Using Array.isArray() method

You can avoid getting the error by checking if the value is an array or not using Array.isArray() method.

The isArray() method will check if the passed value is an array or not.

Example:

export default function App() {
  const obj = { name: "Jack", country: "USA" };

  return (
    <div className="App">
      {Array.isArray(obj)
        ? obj.map((el) => {
            return <p>{el}</p>;
          })
        : null}
    </div>
  );
}

In the above example, the Array.isArray() method checks if the passed value i.e obj is an array or not.

If it’s an array, it will run the map() method on the given array else it will return null.

Conclusion:

In order to avoid the «TypeError: obj.map is not a function» error in React, make sure that the map() method is called only on iteratble object like an array only and that the array is not empty.

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

The freeCodeCamp Forum

Loading

Понравилась статья? Поделить с друзьями:
  • Map construction ошибка dxt2
  • Map construction samp ошибка
  • Manufacturer control ошибка
  • Manual method unavailable ошибка
  • Manual control ошибка