Jorge Vasquez
Jorge Vasquez

Reputation: 15

I can't get my API data to render with the map function React.js

The API does not render and it says this.state.weather.map is not a function. I need help, I have tried different ways of mapping through but does not change the outcome. Any feedback?

import React from 'react';
import axios from 'axios';
              
export default class Weather extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      weather: []
    }
  }
                
  async componentDidMount(){
    axios.get("http://api.weatherapi.com/v1/current.json?key=?=nyc").then(res => {
      console.log(res);
      this.setState ({weather: res.data})
    });
  }

  renderWeather(){
    this.state.weather.map(weather => {
      return (
        <p>{weather.location.name}</p>
      )
    })
  }

  render () {
    return (
      <div>
        {this.renderWeather()}
      </div>
    )
  }
}

Upvotes: 0

Views: 699

Answers (2)

Patrick
Patrick

Reputation: 377

The API returns JSON.

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

Check the typeof res.data. Is is probably not an array but an object, hence this.state.weather.map is not a function, because Array.map() is an array method.

Make sure that you set the state properly to an array and it should work just fine..

Upvotes: 0

Sunil Kumar
Sunil Kumar

Reputation: 420

renderWeather(){
    return this.state.weather.map(weather => {
        return(
            <p>{weather.location.name}</p>
        )
    })
  }

you have missed the return statement inside the renderWeather function, above snippet works for you

Upvotes: 1

Related Questions