Gillian
Gillian

Reputation: 411

How to display data from API endpoint using Axios and React

I'm currently running through this tutorial - https://appdividend.com/2018/11/11/react-crud-example-mern-stack-tutorial/#React_CRUD_Example

I've substituted in my own API and i've successfully managed to create new records. I'm now trying to view a list of all the records but getting the following error

Screenshot of error message

Here is the code (exact copy of tutorial code except API link)



    import React, { Component } from "react";
    import axios from "axios";
    import TableRow from "./TableRow";

    export default class Index extends Component {
      constructor(props) {
        super(props);
        this.state = { address: [] };
      }
      componentDidMount() {
        axios
          .get("http://localhost:6505/api/v1/Address")
          // .then(res => console.log(res))

          .then(response => {
            this.setState({ address: response.data });
          })
          .catch(function(error) {
            console.log(error);
          });
      }
      tabRow() {
        return this.state.address.map(function(object, i) {
          return ;
        });
      }

      render() {...}

If i add in the line that's commented out above '.then(res => console.log(res))', the error message no longer shows and the page renders but without any data - see screenshot below of page and console. I've highlighted the new error message and also highlighted where the data is that i want to display.

Any pointers are greatly appreciated :)

enter image description here

Upvotes: 0

Views: 623

Answers (2)

Ashwanth Madhav
Ashwanth Madhav

Reputation: 1134

The .map function is only available on array.

It looks like data isn't in the format you are expecting.

can you try with consoling response.data or response.data.results.

Can you replace this.setState({ address: response.data }); with this.setState({ address: response.data.results });

Upvotes: 0

Murtaza Hussain
Murtaza Hussain

Reputation: 4315

Your data is in response.data.results so change it to this and it will work.

Thanks

Upvotes: 1

Related Questions