1

Custom Hook in React for calling API — useApi

 3 years ago
source link: https://hackernoon.com/custom-hook-in-react-for-calling-api-useapi-tj1e3103
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Custom Hook in React for calling API — useApi

12
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png

@rugvedRugved Bongale

Developer

Introduction

In this blog we will learn about what is a custom hook and build one — useApi — to fetch data from API with reusable logic.

1 reactions
1heart.png
light.png
money.png
thumbs-down.png

useApi — to fetch data from API with reusable logic.

What is a custom hook?

A custom hook is a JavaScript function whose name starts with “use” and that may call other hooks. A custom hook allows you to extract some component's logic into a reusable function.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

In simple terms, it is the react way of writing reusable logic that can be shared among different components.

What are we building?

We will build a custom hook called useApi which will make the usual repetitive API fetch code reusable.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

What API are we using?

We will use https://jsonplaceholder.typicode.com/users which is a free online REST API that you can use whenever you need some fake user data.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

If you go to the above-mentioned URL, it will return an array of users. First, the user object’s structure is shown below.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

To understand the benefits of custom hooks, let’s look at how to do an API call

One of the most basic things we need is a way to call get data from a server and while it is being fetched from the server, we show a loading screen. We usually need this repetitively at various places on the website.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

So what we usually do when we need to fetch data is:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
  1. Show loading screen.
  2. Call the API.
  3. Once we get data from the server.
  4. Stop loading.
  5. Render/use data based on the use case.
// App.js
import { useEffect, useState } from "react"

const App = () => {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)

  const fetchApi = () => {
    fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => {
      return response.json()
    })
    .then(json => {
      console.log(json)
      setLoading(false)
      setData(json)
    })
  };

  useEffect(() => {
    fetchApi();
  }, []);

  if(loading) return <h1>Loading</h1>

  return <div>
    <h1>Data fetched successfully.</h1>
    {JSON.stringify(data)}
  </div>
};

export default App;

If you print the data in the browser console, this is what the API returns.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Well, everything seems fine but think of a situation where we have a lot of API calls in various parts of the code base. In that case, we need to write this fetchApi function, loading, response data logic again and again. We we are repeating ourselves. Rather what we could do is think of a way to reuse the logic. Also, the code file gets unnecessarily cluttered. That’s what brings us to the need for a custom hook.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Custom Hook approach

Create a new file “useApi.js”. Note that it is necessary to start this name with “use”.We simply pasted our App.js code in this file and made a few changes. One change you can see is that this returns some variables rather than JSX.

0 reactions
heart.png
light.png
money.png
thumbs-down.png
// useApi.js
import { useEffect, useState } from "react"

const useApi = (url) => {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)

  const fetchApi = () => {
    fetch(url) // 'https://jsonplaceholder.typicode.com/users'
    .then(response => {
      return response.json()
    })
    .then(json => {
      console.log(json)
      setLoading(false)
      setData(json)
    })
  };

  useEffect(() => {
    fetchApi();
  }, []);

  return { loading, data }
};

export default useApi;

To understand why we need this file, think of it as a file containing reusable code. This is where we have extracted the code which was going to be repeated everywhere but now it's all in one file.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

All we need to do now is just call this useApi in App.js and remove the fetch logic as we have extracted it into our custom hook useApi.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

New App.js

0 reactions
heart.png
light.png
money.png
thumbs-down.png
// App.js
import useApi from './useApi'

const App = () => {
  const { loading, data } = useApi('https://jsonplaceholder.typicode.com/users')

  if(loading) return <h1>Loading</h1>

  return <div>
    <h1>Data fetched successfully.</h1>
    {JSON.stringify(data)}
  </div>
};

export default App;

We clearly see that number of lines of code has been reduced and the code looks cleaner. That’s the power of custom hooks.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

You can make this hook highly customisable by adding the different parameters of the fetch API like methods, headers, body, etc, but for now, I will keep it simple for easy understanding of the need and concept of custom hooks.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Done!

0 reactions
heart.png
light.png
money.png
thumbs-down.png

That’s all for this blog. If you found this blog helpful, clap and share it with your friends.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

This blog was initially published at https://www.gyaanibuddy.com/blog/custom-hook-in-react-js-for-calling-api-useapi/

0 reactions
heart.png
light.png
money.png
thumbs-down.png
12
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png
by Rugved Bongale @rugved. DeveloperRead my stories
Join Hacker Noon

Create your free account to unlock your custom reading experience.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK