1
votes

please help :)

I'm doing simple Axios get request, in a "Component Did Mount". In a simple/basic react app. I'm trying to get FourSquare place data for London.

My function works, as I can console.log data. Here's my component did mount code:

// FOURSQUARE COMPONENT DID MOUNT
componentDidMount() {
  console.log('COMPONENT DID MOUNT');
  axios.get('https://api.foursquare.com/v2/venues/explore…')

  .then(res => {
   console.log('data', res.data.response.groups[0].items);
// console.log('data',res.data.response.groups[0].items[0].venue.name);
   this.setState(
   { places: res.data.response.groups[0].items}
  );
 });
}

Please here the screenshot attached of console.log. https://i.imgur.com/DPPxwdW.png

However, I'm trying to map through the data, to get "venue.name" in the object array/res.data. But I keep getting the following error:

Cannot read property 'map' of undefined

Here is how I'm trying to map through the data....

const Loaders = ({places}) => {

  return (

    <section>
      <div className="columns is-multiline">
        {places.map((place, i) => <div className="column is-one-quarter" key={i}>
          <ul>
            <li>
              <div className="card-image">
                <figure className="image">
                 <h2 className="has-text-centered has-text-grey">title: {place.venue.name}</h2>
                </figure>
              </div>
            </li>
          </ul>
        </div>)}
      </div>
    </section>
  );
};

export default Loaders;
2
your "places" variable is invalid (not an array)... Can you check if the variable getting the correct data? Ex: dumping the places.length to the view..Anderson Ivan Witzke

2 Answers

0
votes

The reason that happens because it the request is asynchronous and after the response is obtained then the places state is set. So initially, places is undefined. You can render a loading indicator in the loading state

const Loaders = ({places}) => { if(!places){ return Loading... }

return (

<section>
  <div className="columns is-multiline">
    {places.map((place, i) => <div className="column is-one-quarter" key={i}>
      <ul>
        <li>
          <div className="card-image">
            <figure className="image">
             <h2 className="has-text-centered has-text-grey">title: {place.venue.name}</h2>
            </figure>
          </div>
        </li>
      </ul>
    </div>)}
  </div>
</section>

); };

or initialize places to empty array in the constructor

constructor(props) {
   this.state = {
     places = []
   }
}
0
votes

The problem is that this.state.places is undefined at some point. The problem could be the initial state not being set to an empty array at the start or something in the logic changing the value of places. Try to

class Foo extends React.Component {
    state = {
        places: []
    }

    render() {
        return <Loaders places={this.state.places} />>
    }
}