React Custom Hook for Fetching data

From Logic Wiki
Jump to: navigation, search
import { useEffect, useState } from "react";

interface Post {
  id: number;
  title: string;
  post: string;
}

export default function useFetch() {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState<Post[]>([]);

  useEffect(() => {
    setIsLoading(true);

    fetch("/api/posts").then(async res => {
      if (res.ok) {
        const post = await res.json();
        setData(post);
      }
    }).finally(() => {
      setIsLoading(false);
    })
  },[])

  return { isLoading, data };
}