nextjs-demo

next.js demo using react 19 rc

git clone https://9o.is/git/nextjs-demo.git

fetch.ts

(970B)


      1 import { useEffect, useState } from "react"
      2 
      3 export function useFetch<T>(url: string) {
      4     const [data, setData] = useState<T | undefined>()
      5     const [error, setError] = useState<Error | undefined>()
      6     const [loading, setLoading] = useState(false)
      7 
      8     useEffect(() => {
      9         const controller = new AbortController()
     10         const signal = controller.signal
     11 
     12         const fetchData = async () => {
     13         setLoading(true)
     14 
     15         try {
     16             const response = await fetch(url, { signal })
     17             
     18             if (!response.ok) {
     19             throw new Error("Bad request")
     20             }
     21 
     22             setData(await response.json())
     23             setError(undefined)
     24         } catch (error) {
     25             setError(error as Error)
     26         } finally {
     27             setLoading(false)
     28         } 
     29         }
     30         
     31         fetchData()
     32 
     33         return () => controller.abort()
     34     }, [url, setData, setError, setLoading])
     35 
     36     return { data, error, loading }
     37 }