Skip to content

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

Open
@Dev-Dipesh

Description

@Dev-Dipesh

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

Dev-Dipesh commented on Apr 12, 2024

@Dev-Dipesh
Author

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

ByteGrad

ByteGrad commented on Apr 18, 2024

@ByteGrad
Owner

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @Dev-Dipesh@ByteGrad

        Issue actions

          ISSUE: No need to yell at typescript with `as const` · Issue #6 · ByteGrad/Professional-React-and-Next.js-Course