0

i'm new with react and api. i try to get an api with fetch from mongodb. the console.log is ok, but i bug to render it.

import React from 'react';

class Api extends React.Component {
  componentDidMount() {
    const apiUrl = 'https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cv-xfzvw/service/cv/incoming_webhook/api?secret=cv';
    fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => console.log('This is your data', data));
  }
  render() {
    return {data};
  }
}
export default Api;

Does anyone know how how to return body ? Thank you for your help.

1
  • 1. Create a local state of the component. 2. In the componentDidMount, when the data is available in the 2nd then() method's callback function, update the state. 3. Render the data from the state in the render() method. Commented Sep 15, 2021 at 11:24

2 Answers 2

1

I'm no expert on the topic, but as far as I can see from render you need to return a component. Additionally, you might first want to save your api response data to state, and then use it. From the code above, "data" does not have any visibility in your render method.

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

Comments

0

you need to define local status in your class component first, then use setState to set the value. When state value changed, the component will be re-rendered, the render() will refresh the value on browser.

try this:

import React from "react";

class Api extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  componentDidMount() {
    const that = this;
    const apiUrl =
      "https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cv-xfzvw/service/cv/incoming_webhook/api?secret=cv";
    fetch(apiUrl)
      .then((res) => res.json())
      .then((json) => {
        that.setState({ data: JSON.stringify(json) });
      });
  }
  render() {
    return <div>my data: {this.state.data}</div>;
  }
}
export default Api;

Comments

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.