Fetch Data With React Hooks
Overview
Functional component and hooks are now the trending feature of react and it provides an elegant way to do things that we have been doing with class Component's with amount of code. Let's crate a reusable hook that's only job will be to fetch data and it will take only one argument which is url .
Project Creation
Let's create a project with npx create-react-app
create a file name hooks.js
inside of our /src/
folder.
useFetch hook
import {useState, useEffect} from 'react';
function useFetchAPI(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
useEffect(() => {
fetchUrl().then()
}, [url]);
return [data, loading];
}
export {useFetchAPI}
Photo Component
Create a component called Photo.jsx
inside of /src/
folder
import React from "react";
import { useFetchAPI } from "./hooks";
function Photo() {
const [data, loading] = useFetchAPI(
"https://jsonplaceholder.typicode.com/photos?albumId=1"
);
return (
<>
<h1>Photos</h1>
{loading ? (
"Loading...!!!!"
) : (
<ul>
{data.map(({ id, title, url }) => (
<li key={`${id}`}>
<img alt={title} src={url} />
</li>
))}
</ul>
)}
</>
);
}
export default Photo;
Output:
Now if we connect our Photo
component we would see the output.
Conclusion:
Hope this helps to understand hooks a bit more. See you in next post.