ByteGrad / Professional-React-and-Next.js-Course

This repo contains everything you need as a student of the Professional React & Next.js Course by ByteGrad.com
https://bytegrad.com/courses/professional-react-nextjs
139 stars 69 forks source link

ISSUE: No need to yell at typescript with `as const` #6

Open Dev-Dipesh opened 5 months ago

Dev-Dipesh commented 5 months ago

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];
}
Dev-Dipesh commented 5 months ago

Also should use the cleanup function to avoid memory leaks as shown in the full code.

ByteGrad commented 5 months ago

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!