Sunday, May 30, 2021

React (Class ) Fetch Data From An API With React Hooks | AJAX and APIs

 


import React, { Component } from "react";

export default class Planets extends Component {
  state = {
    hasErrors: false,
    planets: {}
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts"
      .then(res => res.json())
      .then(res => this.setState({ planets: res }))
      .catch(() => this.setState({ hasErrors: true }));
  }

  render() {
    return <div>{JSON.stringify(this.state.planets)}</div>;
  }
}

No comments:

Post a Comment

Fetching JSON data from REST APIs

data.json---------------------------------- [     {     "userId" : 1 ,     "id" : 1 ,     "title" : "sunt...