How to make custom hook of Fetch in React JS
In this article, we are going to learn how to make custom hook of Fetch in React JS
In this article ,we are going to make the react snippet which allows us to make the custom hook of Fetch,All we need is to provide the custom hook a url,its automatically done all process of fetch
Example.js file is displayed below:
1import React, { useState, useEffect } from "react";
2import { useFetch } from "./useFetch";
3
4const url = "https://course-api.com/javascript-store-products";
5
6const Example = function () {
7 const { loading, content } = useFetch(url);
8 console.log("data here..", content);
9 return (
10 <>
11 <div>{loading ? "loading......" : "data here"}</div>
12 <div>
13 {content.map((res) => {
14 return res.id;
15 })}
16 </div>
17 </>
18 );
19};
20export default Example;
useFetch.js file is displayed below
1import React, { useState, useEffect, useCallback } from "react";
2export const useFetch = (url) => {
3 const [content, setContent] = useState([]);
4 const [loading, setLoading] = useState(true);
5 const get = useCallback(async () => {
6 const res = await fetch(url);
7 const jsonRes = await res.json();
8 setContent(jsonRes);
9 setLoading(false);
10 }, [url]);
11 useEffect(
12 () => {
13 get();
14 },
15 [url],
16 [get]
17 );
18
19 return { loading, content };
20};
App.js file is displayed below
1import "./styles.css";
2import Example from "./example";
3export default function App() {
4 return (
5 <div className="App">
6 <>
7 <Example />
8 </>
9 </div>
10 );
11}
Here is the link of live example which we done so far:
Click here
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: