Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to call web API with useEffect hook in React TypeScript?

The post How to call web API with Useeffect hook in React TypeScript? appeared first on Cynoteck.

In this article, we would like to introduce you to a sought-after Hooks in a React world known as useEffect & useState hook which are widely used in React Programming, and to get you started towards the path of adding additional types for your TypeScript coding standards. So, Let’s Begin. 

In the world of React Developers, Web Application Programming interfaces (APIs) are interior pieces of code on a single-page application (SPA) design. APIs are the initial stage for applications to programmatically interact with servers to provide programmers with real-time data & to save a programmer’s changes. In a React App, you can use APIs to load programmer’s preferences, display user’s information fetch configuration details or security information & save application’s state updates or changes.

So, what are we exactly going to do:

We will use the useEffect and useState Hook to fetch and display information in our dummy web application using JSON Placeholder’s API for our learning purpose. We’ll need to load information when a component first mounts and saves a customer’s inputs with an API. We can assure you that after the end of this blog you’ll be able to create your own React Application for a variety of APIs.

Things to know first, before we move on to the practical implementation:

What is useEffect?

The useEffect Hook is a hook in React which allows you to execute side effects in your React components.

Examples of side effects such are: 

1. Fetching data from somewhere.

2. Directly updating something to the DOM.

3. Setting or Remove Timers such as setTimeout or setInterval.

useEffect hooks accept the two arguments. The first argument is a function that is mandatory, and the second argument is dependency, or some call it a dependency array by its this [] structure although it’s optional but very useful and handy.

If, No Dependency array is Passed then:

useEffect(() => {
  //It will Run or Execute on every render or every time.
});

If, Empty Array is Passed then:

useEffect(() => {
  //It will Run or Execute only on the first render or for just one time.
}, []);

Example:

import React, { useState, useEffect } from 'react';

export const App = () => {
  const [result, setResult] = useState();
  useEffect(() => {
    add();
  });

  function add() {
    const a: number = 5;
    const b: number = 10;
    setResult(a + b);
  }
  return (
    

Added Sum is: {result}

); };

CodeSandbox Link:

https://stackblitz.com/edit/react-starter-typescript-xtuqtv?file=App.tsx

Output:

Also, read: Laravel Web App into Mobile App – Top Transformation Scenarios

What is useState?

The useState Hook in React allows us to track state in a function component.

The state basically refers to important data or a specific piece of information in an application. 

Example: If the switch of a Fan is OFF, so its state is in Off and it won’t be rotating anymore. 

Same way, if you switch it ON, its previous state of OFF will now change to ON and the fan will keep on rotating, right?

Again, useState Hook takes two arguments:

First, A Variable, where it will store the data.

Second, A Function for setting the value of that particular variable.

Example:

import React, { useState } from 'react';

export const App = () => {
  const [name, setName] = useState('Akshay Bisht');
  return (
    

My Name is {name} 😎

); };

CodeSandbox Link:

https://stackblitz.com/edit/react-starter-typescript-yekrro?file=App.tsx

Output:

What is a RESTful API?

RESTful API, you have surely heard this term a lot of times when you have met someone who has a designation as a Backend Developer. You would have been asking yourself (What is this API thing? Why should we need to use it? How will it help me?)

Well, let us now explain to you in a brief and clear your doubts:

API is known as Application Programming Interface. Nowadays, it’s a very trending and useful technique to interact with a user’s data. Earlier we used to update our database by mostly writing boring SQL commands, which are not easy for every person in the world to remember.

So as an Alternative, NoSQL Databases like MongoDB, Cassandra, Redis, CouchDB, Riak, and many more have been introduced. So, if there will be NoSQL why do you need it? How will you interact with it? Well, if the Database is NoSQL, then definitely there is an alternate way to access this type of Database and that way is RESTful API.

Yes, you have heard it correctly. That’s how the RESTful API has been introduced to the programmers and it was a much more easy, robust, and code-friendly approach.

So, from then, it is now a trend to use API’s, most of the companies nowadays use them. And the person who interacts with API is known as a Backend Developer.

In API, the fun part is that it gives you an HTTP status code from which you can identify where the Data has been fetched or not, what kind of error you are getting.

HTTP methods that are taken by any API:

GET – It is a method used for getting Data from a Database.

POST – It is a method used for creating or inserting data into Database.

PUT – It is a method in which we can update or correct a specific field of data and then send that updated data to the Database. 

DELETE – It is a method in which we can delete the record or data of a user from the Database.

Following are such a HTTP Status Codes:

  • 200 – OK
  • 201 – Created
  • 302 – Found
  • 400 – Bad Request
  • 401 – Unauthorized
  • 403 – Forbidden
  • 404 – Not Found
  • 500 – Internal Server Error
  • 502 – Bad Gateway

Also, read: Microservices vs API – know what’s right for your business

What is DOM?

DOM is known as Document Object Model; it is basically created by the browser when we load any webpage. It follows the tree structure of an HTML Document, so that it can compile it, and can be easy for the Front-End Developers to inspect and find the specific component very easily. React follows the Virtual DOM, and it is a very lightweight representation of the actual DOM. So, we will be focusing less on these topics.

This is how DOM looks:

So here comes the practical part:

We will initially get your code run first. After that, we will explain each point to you so that you can understand what we have written in the code clearly.

So, let’s jump into the code. And then the explanation part.

Steps 1:

Create a React TypeScript Application on your system by the following command:

npx-create-react-app –template typescript

Steps 2:

Go to your React Typescript Application Directory and Install a bootstrap package by following command:

npm install bootstrap

Steps 3:

In your App.tsx file, clear all the code and paste the below code:

import React, { useEffect, useState } from 'react';

interface user {
  map(arg0: (item: any) => JSX.Element): import('react').ReactNode;
  name: string;
  email: string;
  phone: number;
}

export const App = (): React.FC => {
  const [user, setUser] = useState();
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((json) => setUser(json));
  }, []);

  return (
    
{user?.map((item) => ( ))}
S.no Name Email Phone
{item.id} {item?.name} {item?.email} {item?.phone}
); };

Steps 4:

Now to get started and see your final output on the screen just type in the following command:

npm start

Steps 5:

Now just wait for the output and after some time, you will see output like this: 

CodeSandbox Link:

https://stackblitz.com/edit/react-starter-typescript-emeoep?file=App.tsx

Explanation:

So, what is happening here? We have just shown our Bootstrap table with 10 users’ dummy data with a JSONPlaceholder user’s API. 

Initially, we have just created an interface so that we can tell typescript that what we will get is this data in a response like a name of the string, email of a string, and a phone number of a number. 

After that, we declared a variable and set the Function of a useState hook to store the response coming from the API and for using it later. And in the useState hook, we told the typescript that follows our interface named as “user” and later on I set the response data onto my setFunction so that we can use it below in our bootstrap table. 

Then, in the Below Bootstrap Table, we just loop over an object and access them with the variable that we just set above in my useEffect hook method. And we just access the object’s values. And finally, when we save the code, it rendered.

Also, read: Laravel 8 – Excel and CSV Import Export to Database tutorial

Conclusion

In the end, we would just like to wrap up the things by saying that API calls are easy until and unless you do not play with a useEffect and useState hook in a react typescript and practice it in your daily routine. Both hooks are very essential for the API Calls to store or interact with. We hope now your concepts have become much clearer and more concise.

Thank you so much for reading this blog so patiently , Have a good day .

Web Development Services

Are you looking for a reliable web development company? Our highly skilled web developers enables us to deliver result oriented web development services. Contact our team to understand, how we can help you in achieving your business goals.

Get a consultation >


RELATED BLOGS

Blogs

How to call web API with useEffect hook in React TypeScript?

Blogs

Laravel Web App into Mobile App - Top Transformation Scenarios

Blogs

Laravel 8 - Excel and CSV Import Export to Database tutorial

Load More


This post first appeared on CRM Consultant, please read the originial post: here

Share the post

How to call web API with useEffect hook in React TypeScript?

×

Subscribe to Crm Consultant

Get updates delivered right to your inbox!

Thank you for your subscription

×