3

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?
    );
}
}
1
  • 1
    Did you try consoling response coming from api ? I think you'll get in res.data and then you can setState it into response state. Commented Mar 13, 2020 at 4:19

4 Answers 4

3

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>
    );
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Can you check the network tab, what are yo getting the response .
its localhost:5000/api, i did a console log to my react js file. im currently using express, not sure why console log only appeared in my express backend side but not for my react frontend
Oh dear, i did a console log res.data im not retrieving anything on my frontend. I did a log at my backend i seems to be fine though.
Im not sure how to put it, but its 500 lines of code. In short, i have two post api in the backend. The first api works completely fine. But the second api seems to be not sending any data, im using res.end(JSON.stringify(data)); to send the API response above
|
1

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>
);
}
}

3 Comments

I tried the response.map.. but i got the same error earlier. TypeError: this.state.response.map is not a function
log the outpot using console. Response coming has some different structure. Its not an array looks like
@scorezel789 i faced the same error few days ago, map function works on array object that is why you are getting this error. Check your code, you must be applying map function on wrong json object.
1

--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>
        );
    }
}

2 Comments

I believe your code should work but im not sure why im getting this error TypeError: Cannot read property 'map' of undefined. Did this code worked on your side?
Please check your json response as below. axios .post(url, seedURL) .then((res) => { this.setState({ responses: res, error: null }) console.log(res); }) .catch((err) => { this.setState({ error: err, response: null }) console.log(err); });
1

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

2 Comments

Hi Juan! Thanks for highlighting what is needed to be done! I found my error. Turns out that i my response did not went through the front end. I did console log and managed to fixed the error. I was passing an empty array all this while (:
That's great to hear.....we all make mistakes...sleeping helps xD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.