4 ways to fetch Data in React.
Netsai
Posted on January 31, 2023
Fetch API.
It is the basic way to fetch data in react and javascript.
Fetch API can be used without installing any other react library.
It's built into javascript.
You should have the URL for the API which you want to fetch data from.
You just write the fetch function and add the URL.
Fetch API returns a promise and after the promise has been resolved we have to transform the data to JSON.
I will show it on the component below.
import React, { useEffect, useState } from "react";
function Fetch() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://cat.ceo/api/breeds/image/random")
.then((resp) => resp.json())
.then((apiData) => {
setData(apiData.message);
});
}, []);
return (
<div>
<img width={500} src={data} />
</div>
);
}
export default Fetch
So Fetch API is a simple way to fetch data.
Axios.
It is a common react library used to fetch data.
Installing Axios is the first stage before using it in the code.
$ npm install axios
$ yarn add axios
Then import axios from axios library.
We use the get/post/put/delete method inside the useEffect to get the data for the URL.
It will return a promise differently from fetch because axis handle and change it to JSON
import React, { useEffect, useState } from "react";
import axios from "axios";
function Axios() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get("https://cat.ceo/api/breeds/image/random").then((resp) => {
setData(resp.data.message);
});
}, []);
return (
<div>
<img width={500} src={data} />
</div>
);
}
export default Axios;
SWR Library.
It stands for stale while we're validate.Before anything else we have to install the SWR library.
$ yarn add swr
We import the SWR hook from swr. There is no need of useEffect and useState hook because its all built into the library.
Any type of fetcher can be used e.g axis .Even the useSWR is the way to handle data and the Fetch API is for making request.
We use the library as follows
import React, { useEffect, useState } from "react";
import useSWR from "swr";
const fetcher = (...args) => fetch(...args).then((resp) => resp.json());
function Swr() {
const { data, error } = useSWR(
"https://dog.ceo/api/breeds/image/random",
fetcher,
{
suspense: true,
}
);
if (error) {
return <h1> There was an error!</h1>;
}
return (
<div>
<img width={500} src={data.message} />
</div>
);
}
export default Swr;
React Query library.
It fetches ,caches and update data in react and react native applications with out using global state e.g useState, useEffect.
We install this library by using the below commands in react app.
$ yarn add react-query
$ npm install react-query
It uses other fetchers such as axis and fetch to get data from the expected URL.
Benefits of using react query in our react application
- Ease of fetching data
- It is becoming the standard way to fetch data
- Fun ways of fetching data
- Highly customizable
- Lightweight
import React, { Fragment } from "react";
import axios from "axios";
import { useQuery } from "react-query";
export default function Repositories() {
const { isLoading, isError, data, error, refetch } = useQuery(["repo"], () =>
axios
.get("https://api.github.com/users/eunit99/repos")
.then((res) => res.data)
);
if (isLoading) return "Loading...";
if (error) return "An error has occurred: " + error.message;
console.log(data)
return (
<>
{data.map(repo => {
return (
<Fragment
key={repo.id}
>
<ul>
<li>
<a
href={repo.clone_url}>
{repo.name}
</a>
</li>
</ul>
</Fragment>
)
})}
<button type="button" onClick={refetch}>
Fetch again
</button>
</>
);
};
So this is the information I can share with others concerning the ways to fetch data
Goodbye 🙌
Posted on January 31, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024