Search code examples
axiosfetchmern

How can I re-write this method using fetch?


In my react app i'm using axios for requests to the server.

  // This method will get the data from the database.
  componentDidMount() {
    axios
      .get("http://localhost:3000/record")
      .then((response) => {
        this.setState({ records: response.data });
      })
      .catch(function (error) {
        console.log(error);
      });
  }

How can I re-write this method using fetch?


Solution

  • fetch('http://localhost:3000/record')
      .then(response => {
            this.setState({ records: response.data });
          })
      .catch(function (error) {
            console.log(error);
          });;
    

    Check this link if you want to use other request methods.