API in Class Component

class component api


In React, the class components and lifecycle methods have changed quite a bit in the last few years. Often times a developer may be handling legacy code and the newer paradigm of functional components and hooks.
 

Class(stateful) Component
Class component can be described as an ES6 class. The class component has a state and a lifecycle. In the older versions of React (version < 16.8), it was not possible to use state inside functional components. Therefore, functional components was majorly used for rendering UI only, whereas we’d use class components for data management and some additional operations (like life-cycle methods). With the introduction of React Hooks, and now we can also use states in functional components as well.

A Class Component:

  • is an ES6 class, will be a component once it ‘extends’ a React component.
  • takes Props (in the constructor) if needed must have a render( ) method for returning JSX

    Class Component

    • Takes advantage of object oriented programming
    • Creates objects via constructor function, a built in JavaScript class method
    • The 'class', 'constructor', 'super', 'this' and 'new' keyword are needed
    • JSX is returned in the render statement
    • The render lifecycle must be managed explicitly
    • Use the setState and will merge the state
    • Method Binding

      Fetching () API ::

       
        import React, { Component } from 'react';

        class App extends Component {

          render() {

            fetch('https://jsonplaceholder.typicode.com/todos/1')
              .then(response => response.json())
              .then(json => console.log(json))

            return (
              <div>
               
              <h2>This is class component </h2>


              </div>
            );
          }
        }

        export default App;

       
API in with Map() in our Component

 
  import React, { Component } from 'react';

  class App extends Component {

    constructor(props){
      super(props);
      this.state = {posts:[]};
    }

    componentDidMount(){
      fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(response => this.setState({posts:response}))
    }


    render() {

      return (
        <div>
         
        <h2>This is class component </h2>
        {
          this.state.posts.map(post=> <div>{post.id}.{post.title}</div>)
        }


        </div>
      );
    }
  }

  export default App;