简体   繁体   中英

Unhandled Rejection (TypeError): Cannot read property '0' of undefined happening while trying to load API data with Axios on ReactJS

Trying to load the Open BreweryDB API in a ReactJS application to display a list of breweries in a US city. Loading the information using axios and the async componentDidMount() method results in the "Unhandled Rejection (TypeError): Cannot read property '0' of undefined" error at line 34 (in my code) which would be breweryData = breweryData.data.results[0];

I'm pretty new to ReactJS and API implementation. I tried removing the ...results[0]; portion, but I still got the same error as above, with an issue on the same line. Not sure how to solve this issue. I'm able to render a "Loading..." element on the card if I ignore the error. Below is the code I am using in my App.js folder


import API from './utils/API';
import Brewery from './component/Breweries';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      name: null,
      address: null,
      brewery_type: null
    };
  }

  render() {
    const { isLoading, name, address, brewery_type } = this.state;

    return (
      <Brewery isLoading={isLoading} name={name} address={address} brewery_type={brewery_type} />
    );
  }

  async componentDidMount() {
    let breweryData = await API.get('/', {
      params: {
        results: 1,
        inc: 'name,address,brewery_type'
      }
    });

    breweryData = breweryData.data.results[0];

    const name = `${breweryData.name}`;
    const address = `${breweryData.address}`;
    const brewery_type = `${breweryData.brewery_type}`;

    this.setState({
      ...this.state, ...{
        isLoading: false,
        name,
        address,
        brewery_type
      }
    });
  }
}

export default App;

It should display a list of results displaying the name of the brewery, the address, and the brewery type (micro, major, etc.)

Above issue was fixed, however, the API data is not displaying. Here is the code in the breweries.js file

import PropTypes from 'prop-types';

import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

import { Card } from 'shards-react';

class Brewery extends React.Component {
    render() {
        const { name, street, city, state, postal_code, isLoading } = this.props;

        const breweryDetails = (
            <div>
                <h4 className="mb-0">{name}</h4>
                <span className="text-muted">{street}</span>
                <span className="text-muted">{city}</span>
                <span className="text-muted">{state}</span>
                <span className="text-muted">{postal_code}</span>
            </div>
        );

        const loadingMessage = <span className="d-flex m-auto">Loading...</span>;

        return (
            <Card
                className="mx-auto mt-4 text-center p-5"
                style={{ maxWidth: "300px", minHeight: "250px" }}
            >
                {isLoading ? loadingMessage : breweryDetails}
            </Card>
        );
    }
}

Brewery.propTypes = {
    name: PropTypes.string,
    street: PropTypes.string,
    city: PropTypes.string,
    state: PropTypes.string,
    postal_code: PropTypes.string,
    isLoading: PropTypes.bool
};

export default Brewery;

Change

breweryData = breweryData.data.results[0];

to

breweryData = breweryData.data[0]

or even better

let returnedBreweryData = breweryData.data ? breweryData.data[0] : {}

It's maybe because you are not getting the result from API for some reason. When you are using async await, you would want to handle the error too. Add a try catch block to your code and you should be fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM