Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Dev-Dipesh opened this issue Apr 12, 2024 · 2 comments
Open

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

Dev-Dipesh opened this issue Apr 12, 2024 · 2 comments

Comments

@Dev-Dipesh
Copy link

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
Copy link
Author

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

@ByteGrad
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants