Home > Software design >  API POST using fetch helper function doesn't render update after response is received
API POST using fetch helper function doesn't render update after response is received

Time:05-29

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.

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

Thank you!

CodePudding user response:

   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.

CodePudding user response:

Are you sure apiHelper(URLredacted,JSONredacted) returns a promise? Looks like you did the promise handling in the function already.

This should work :

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

  componentDidMount() {
      this.setState({
          apiResponse: apiHelper(URLredacted,JSONredacted)
      });

  }
  render() {
    const jsonResponse = JSON.stringify(this.props.apiResponse)
    return (
    <div>
      <img className="logoheader" src = {logo}/>
      <ColoredLine color="grey"/>
      <p>{jsonResponse}</p>
    </div>
    );
  }
}
  • Related