Professional-React-and-Next.js-Course icon indicating copy to clipboard operation
Professional-React-and-Next.js-Course copied to clipboard

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

Open Dev-Dipesh opened this issue 10 months ago • 2 comments

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 avatar Apr 12 '24 03:04 Dev-Dipesh