REVISITING - TypeError: Cannot read property map of undefined


#1

Hi! I’m revisiting an old question that wasn’t resolved and I’m unsure where I took a wrong turn. I’ve searched extensively and can’t seem to find an answer for this so I’m hoping that someone on here can help me.

I’m doing the Ravenous exercise in the " Building Front-end Applications with React" section of the Web Development Path. When I click on the “Let’s Go” button to execute a search and send a request to Yelp’s API, the request completes just fine and I can see the data return via the network in the dev tools. I’ve even logged out the custom mappings that I’ve created. However, it never maps to the state’s business array and hence never renders the results.

Some posts on Stack Overflow mentioned that the BusinessList component is rendering before the results are returned and to try using a conditional to ensure that this.props.business is truthy before rendering. However, this does not work as console.log(this.props.businesses) returns undefined. Leading me to believe it’s not setting the state correctly.

Can anyone help me figure out why the code does not work?

This is my code below

import React from 'react';
import './BusinessList.css';
import Business from '../Business/Business.js';

class BusinessList extends React.Component {
        render() {
        return (
        <div className="BusinessList"> 
        {
        this.props.businesses.map(business => {
        return <Business key={business.id} business={business} />
            })
        }
        </div>
        );
}
}


export default BusinessList;


import React, { Component } from 'react';
import './App.css';
import BusinessList from './components/BusinessList/BusinessList';
import SearchBar from './components/SearchBar/SearchBar';
import Yelp from './util/Yelp';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      businesses: []
    };
    
    this.searchYelp = this.searchYelp.bind(this);
  }

  searchYelp (term, location, sortBy) {
    Yelp.search(term, location, sortBy).then(businesses => {
    this.setState({businesses: businesses});
    });
 }

  render() {
    return (
            <div className="App">
        <h1>ravenous</h1>
        <SearchBar searchYelp={this.searchYelp} />
        <BusinessList businesses={this.state.businesses}/>
      </div>
    );
  }
}

export default App;


#2

I was having trouble here as well. I tried making the Yelp.search method in Yelp.js an async function with try/catch block but it didn’t fix it. It turns out I misspelt ‘authorization’, omitting the ‘h’ in there and it worked.

I don’t know if the code is still valid without the async keyword as I have not tried it though.