0

I am trying to fetch the message outputted by the following endpoint:

http://helloworld-env-2.5fwknpgms8.us-east-2.elasticbeanstalk.com/

I just ran a create-react-app to create my application and changed the code in the App.js file

New Code:

import React, { Component } from 'react';
import './App.css';

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       error: null,
       isLoaded: false,
       items: ""
    };
  }

  componentDidMount(){
    console.log("mounting component");
    fetch("http://helloworld-env-2.5fwknpgms8.us-east-2.elasticbeanstalk.com/")
    .then((result) => {
      this.setState({
        isLoaded: true,
        items: result
      });
    });
  }

  render() {
    console.log("rendering");
    const isLoaded = this.state.isLoaded;
    if(isLoaded){
      return (<div> {this.state.items} </div>);
    }
    else{
    return (
      <div>loading</div>
    );
    }
  }
}

export default App;

I keep getting the loading message.

1 Answer 1

2

You need to parse the response from fetch:

  componentDidMount(){
    fetch("http://helloworld-env-2.5fwknpgms8.us-east-2.elasticbeanstalk.com/")
    .then((result) => result.json()) // here
    .then((result) => {
      const { a } = result; // access 'a' key from response
      this.setState({
        isLoaded: true,
        items: a
      });
    });
  }

Here are the docs.

Sign up to request clarification or add additional context in comments.

3 Comments

The API response is shaped like this: { a: 'hello world' }, so you need to reference the a key in order to access 'hello world': jsfiddle.net/n5u2wwjg/71686.
@kuiro5 You missed = in between const { a } and result
the same logic is not working when I point to local spring boot project with the URL of localhost:8181/api/hello Let me know if any other options we have?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.