API Calling in React and TypeScript

#day7learningReact

Introduction:

The basic method to request the data is performed using the fetch function of the javascript. The basic syntax of the fetch function is:

fetch(url, options)
  .then(response => {
    //response
  })
  .catch(error => {
    //errors
  });

The fetch function returns a promise. Using '.then' we get the response and it can be formatted to JSON4 format. The catch is to handle errors.

Fetching the data in React:

Suppose we want to fetch the data when the component is loaded then the fetch call can be made within useEffect hook's callback function.

import React,{useEffect} from "react";

export const Card:React.FC= ()=>{
    useEffect(()=>{
    fetch("https://example.com")
    .then((response) => 
    console.log(response)
    );
    },[])
    return(
        <div></div>
    )};
  • Whenever the component is loaded the fetch is made and the fetch returns a promise in a pending state.

  • .then(response) returns an object which might not be in a readable format and needs to be parsed into a certain type of readable data.

import React,{useEffect} from "react";

export const Card:React.FC= ()=>{
    useEffect(()=>{
    fetch("https://example.com")
    .then((response) =>(response)
    .then((e) => e.json())
    .then((res) => console.log(res)
    );
    },[])
    return(
        <div></div>
    )};
  • Here response returns the same result as it is and then it is converted to JSON format.

  • res is the final response in JSON format.

Displaying the requested data in the UI:

To display the data we can create a useState hook and values can be mapped to an HTML element or the component.

import React,{useEffect,useState} from "react";
interface DataRequested{
    key:boolean,
    id:number,
    value:string
}

export const Card:React.FC<DataRequested>= ()=>{
    const[value,setValue]=useState([]);
    useEffect(()=>{
    fetch("https://example.com")
    .then((response) =>(response)
    .then((e) => e.json())
    .then((res) => setValue(res as DataRequested[]));
    );
    },[])
    return(
        <div>
            value.map(val =><li>{val.title}</li>)
        </div>
    )};

Here the result is mapped to the list element. Since the type script demands the type specification the interface 'DataRequested' is created and the type of values in objects is declared.

The component type is set to the interface type and values in the useState value set using the setValue function of type 'DataRequested'.