0

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.

2
  • 2
    I think the data you're getting from api is not of array type. What data did you get in console.log? Commented May 6, 2022 at 21:47
  • I think weather API returns an object Commented May 7, 2022 at 12:42

2 Answers 2

2

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);
        });
}, []);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.