'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.



Solution 1:[1]

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);
        });
}, []);

Solution 2:[2]

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>
 )
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aneesh
Solution 2 Salem_Raouf