Open
Description
Project: rmtdev
Video: 132
Instead of using as const
a far safer alternative is to simply define the return value for the custom hook
export function useFetchJobs(search: string): [JOBITEM[], boolean] {...}
Full Code
// Custom Hook to fetch jobs from the API
import { useState, useEffect } from "react";
import { SEARCH_API } from "../lib/constants";
import { JOBITEM } from "../lib/types";
type DataProps = {
public: boolean;
sorted: boolean;
jobItems: JOBITEM[];
};
export function useFetchJobs(search: string): [JOBITEM[], boolean] {
const [jobs, setJobs] = useState<JOBITEM[]>([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (!search || search.length < 3) return;
const controller = new AbortController();
const signal = controller.signal;
const fetchData = async () => {
try {
setIsLoading(true);
const response = await fetch(SEARCH_API + search, { signal });
const data: DataProps = await response.json();
setJobs(data.jobItems);
} catch (e) {
console.error(e);
} finally {
setIsLoading(false);
}
};
fetchData();
return () => {
controller.abort();
};
}, [search]);
return [jobs, isLoading];
}
Activity
Dev-Dipesh commentedon Apr 12, 2024
Also should use the cleanup function to avoid memory leaks as shown in the full code.
ByteGrad commentedon Apr 18, 2024
Looks good to me at first sight too, thanks. Will take a look at your other suggestions a bit later as well. Great work so far!