scorezel789
scorezel789

Reputation: 163

How to fetch an API response in React?

I'm trying to fetch the following API response data in ReactJS. I'm not sure how to do it.. Can someone help me with this? Thanks in advance, I really appreaciate any help or suggestions given.

For my final output, i want to eventually loop the each of the response in the array and display them just like the API response except in a table which represents each shop with address and postal details.

API Response

[
  {
    title: 'Paragon',
    address: '290 Orchard Road #B1-03 Singapore 238859',
    postal: '238859'
  },
  {
    title: 'BreadTalk IHQ',
    address: '30 Tai Seng Street #01-02 Singapore 534013',
    postal: '534013'
  },
  {
    title: 'City Square Mall',
    address: '180 Kitchener Road #01-10 Singapore 208539',
    postal: '208539'
  }
]

Code (details.js)

class Crawler extends React.Component {

// Create constructor with props
constructor(props) {
    super(props);

    // Create a state that takes in the SEEDURL
    this.state = {
        seedURL: '',
        response: null,
        error: null
    };
}

    // The seed url taken from the input
    const seedURL = this.state;

    // Take the seedURL and send to API using axios
    const url = "/api";

    // Send data using axios
    axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
    try {
        // Axios takes in the url and SeedURL
        axios
        .post(url, seedURL)
            .then((res) => {
                this.setState({response: res, error: null})
            })
            .catch((err) => {
                this.setState({error: err, response: null})
            });
    } catch (e) {
        console.log(e);

render() {
    return(
        // How do i read the response here?
    );
}
}

Upvotes: 3

Views: 3375

Answers (4)

Juan L
Juan L

Reputation: 1731

To add to the previous responses where you will find how to loop through the data, add a proxy property in your package.json with the location of your server

"proxy":"http://localhost:5000/api"

and then just do all your requests with what goes after the /api.....Eg: to fetch data from http://localhost:5000/api/cats just do the fetch to /cats

Also check in chrome for the network tab and make sure your request is being sent

Upvotes: 1

GeeshFedo
GeeshFedo

Reputation: 11

--Try This Code--

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

        // Create a state that takes in the SEEDURL
        this.state = {
            seedURL: '',
            error: null,
            responses: []
        };
    }

    // The seed url taken from the input
    const seedURL = this.state;

    // Take the seedURL and send to API using axios
    const url = "/api";

    // Send data using axios
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
        try {
    // Axios takes in the url and SeedURL
    axios
        .post(url, seedURL)
        .then((res) => {
            this.setState({ responses: res, error: null })
        })
        .catch((err) => {
            this.setState({ error: err, response: null })
        });
        } catch (e) {
            console.log(error);
      this.setState({ error: error.message, response: [] })
    }

    render() {
        const { responses } = this.state;
        return (
            <div >
                <table>
                    <thead>
                        <tr>
                            <th>title</th>
                            <th>address</th>
                            <th>postal</th>
                        </tr>
                    </thead>
                    <tbody>
                        {responses.map(response =>
                            <tr key={response.title - response.postal}>
                                <td>{response.title}</td>
                                <td>{response.address}</td>
                                <td>{response.postal}</td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        );
    }
}

Upvotes: 1

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

You could use componentDidMount lifecycle hook to get the api data on component mount and update the state. The state update will render the component with the updated state.

You cannot add code directly in class body except class fields. you should wrap the code inside a method.

Example:

class Crawler extends React.Component {
  // Create constructor with props
  constructor(props) {
    super(props);
    this.state = {
      seedURL: 'http://localhost:5000',
      response: [],
      error: null
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  async fetchData() {
    const seedURL = this.state.seedURL;
    const url = "/api";
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
    try {
      let res = await axios.post(seedURL + url);
      let data = await res.json();
      console.log(data);
      this.setState({ response: data, error: null })
    } catch (error) {
      console.log(error);
      this.setState({ error: error.message, response: [] })
    }
  }
  render() {
    return (
      <div >
        <table>
          <thead>
            <tr>
              <th>title</th>
              <th>address</th>
              <th>postal</th>
            </tr>
          </thead>
          <tbody>
            {(this.state.response.length > 0) ? this.state.response.map(item => (
              <tr key={item.title + item.postal}>
                <td>{item.title}</td>
                <td>{item.address}</td>
                <td>{item.postal}</td>
              </tr>
            )) : null}
          </tbody>
        </table>
      </div>
    );
  }
}

Upvotes: 3

Anup Das Gupta
Anup Das Gupta

Reputation: 771

Try this-

render() {
    return(<React.Fragment>
{this.state.response && this.state.response.map((r, i)=> <div key={i}>
              <div>{r.title}</div>
              <div>{r.address}</div>
              <div>{r.postal}</div>
          </div>)}
</React.Fragment>
);
}
}

Upvotes: 1

Related Questions