Home > other >  React api fetch
React api fetch

Time:09-16

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.

CodePudding user response:

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.

CodePudding user response:

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;

  • Related