Tom Hanks
Tom Hanks

Reputation: 614

React - .map returning not a function?

I was following this example: https://reactjs.org/docs/faq-ajax.html

But my code is returning weather.map is not a function?

function App(props) {

  const [weather, setWeather] = useState([]);

  useEffect(() => {
    fetch("https://api.openweathermap.org/data/2.5/weather?q=kalamazoo&appid=XXXXXXXXXXXX")
    .then(res => res.json())
    .then(
      (result) => {
      setWeather(result)
      console.log(result)
      }
    )
  },[])

  return (
    <div className="App">
      {weather.map(item => (
        <li key={item.id}>{item.main}</li>
      ))}
      
    </div>
  );
}

export default App;

I understand that it expects an array, but even if the API hasn't returned I still get the error.

Upvotes: 0

Views: 69

Answers (2)

Salem_Raouf
Salem_Raouf

Reputation: 431

map is not a function error mean that that weather data type is not an array so it hasn't a map function the API returning an Object so instead of direct map you can use

Object.values(weather || {}).map((item)=>{
  return(
   <li key={item.id}>{item.main}</li>
 )
})

Upvotes: 0

Aneesh
Aneesh

Reputation: 1715

The openweathermap GET /weather API returns an object. You can check out on their Swagger for details of the APIs and their exact response formats

To access the weather information, you need to do the following:

useEffect(() => {
    fetch(
        'https://api.openweathermap.org/data/2.5/weather?q=kalamazoo&appid=XXXXXXXXXXXX'
    )
        .then((res) => res.json())
        .then((result) => {
            setWeather(result.weather); // this is where weather data array is present
            console.log(result);
        });
}, []);

Upvotes: 2

Related Questions