Mitchell
Posted on November 9, 2024
You can find all the code in this post on the repo Github.
Request-related React custom hooks challenges
useSWR()
import { useState, useEffect } from "react";
function useSWR(_key, fetcher) {
const [data, setData] = useState();
const [error, setError] = useState();
const fetchResult = fetcher();
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetchResult;
setData(response);
} catch (err) {
setError(err);
}
};
if (fetchResult instanceof Promise) {
fetchData();
}
}, []);
const result = fetchResult instanceof Promise ? data : fetchResult;
return {
data: result,
error,
};
}
/* Usage example */
export default function App() {
return <div></div>;
}
useFetch()
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState();
const [error, setError] = useState();
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, error, loading };
}
/* Usage example */
export default function App() {
const { data, error } = useFetch("https://randomuser.me/api/");
return (
<div>
<p>Fetch result: {JSON.stringify(data) ?? error}</p>
</div>
);
}
Reference
💖 💪 🙅 🚩
Mitchell
Posted on November 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.