1

Beginner at React (and JS)...

I am trying to update text on the screen after my API helper function has completed a call. Instead, it returns empty. I have verified with the console that the data is being received. I followed the ComponentDidMount method from other similar questions but am still having no success. My code also seems to make multiple API calls, even though my intent is to only make one; I have to wonder if the issue stems from that.

Helper function:

export function apiHelper(url, data = {}, method = 'POST') {
    return fetch(url, {  // Return promise
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
        .then(res => res.json())
        .then((result) => {
            console.log(result);
            return result;
        }, (error) => {
            error = error;
        })
}

React Component that renders incorrectly after data is received:

class Headache extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      apiResponse: null,
    };
  }

  componentDidMount() {
        apiHelper(URLredacted,JSONredacted)
        .then(response => {
          this.setState({
            apiResponse: response
          });
          console.log("state set.",response)
        });
  }
  render() {
    const jsonResponse = JSON.stringify(this.props.apiResponse)
    return (
    <div>
      <img className="logoheader" src = {logo}/>
      <ColoredLine color="grey"/>
      <p>{jsonResponse}</p>
    </div>
    );
  }
}
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • For anyone that might stumble on my post, this is an issue with a lack of understanding of async calls. https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Drew Bermudez Jun 08 '22 at 00:42

1 Answers1

1
   export function apiHelper(url, data = {}, method = 'POST') {
        return fetch(url, {  // Return promise
            method: method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        })
            .then(res => res.json())
            .catch(err=>console.log(err))
    }

    second page:

class Headache extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      apiResponse: null,
    };
  }

  componentDidMount() {
        apiHelper(URLredacted,JSONredacted)
        .then(response => {
          this.setState({
            apiResponse: response
          });
          console.log("state set.",response)
        });
  }
  render() {
    const jsonResponse = JSON.stringify(this.props.apiResponse)
    return (
    <div>
      <img className="logoheader" src = {logo}/>
      <ColoredLine color="grey"/>
      <p>{jsonResponse && ""}</p>
    </div>
    );
  }
}
 if these code dont work you will be need asyn function because you need to wait to fetch data.
Hazrat Gafulov
  • 318
  • 4
  • 9
  • Thanks, unfortunately doesn't work. Not sure what you mean by needing an async function. From other code examples, I've seen componentDidMount as a solution for handling the delayed API response, but it's unclear to me why it doesn't work here. – Drew Bermudez May 29 '22 at 02:10