I have created a custom hook to fetch data from the provided uri. But the issue is that the component which is using this custom hook is being rendered twice.
Codebase
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
function useFetch(uri) {
const [data, setData] = useState();
const [error, setError] = useState();
const [loading, setLoading] = useState();
useEffect(() => {
if (!uri) return;
setLoading(true);
fetch(uri)
.then((res) => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [uri]);
return { data, error, loading };
}
const App = ({ login }) => {
const { data, error, loading } = useFetch(
`https://api.github.com/users/${login}`
);
if (loading) return <h1>Loading...</h1>;
if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
console.log(data?.login);
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
ReactDOM.render(
<React.StrictMode>
<App login="ziishaned" />
</React.StrictMode>,
document.getElementById("root")
);
