import { useState, useEffect, useCallback } from 'react'

export function useApi<T>(url: string, defaultValue: T): { data: T; loading: boolean; refetch: () => void } {
  const [data, setData] = useState<T>(defaultValue)
  const [loading, setLoading] = useState(true)

  const refetch = useCallback(() => {
    setLoading(true)
    fetch(url)
      .then(r => r.json())
      .then(d => { setData(d); setLoading(false) })
      .catch(() => setLoading(false))
  }, [url])

  useEffect(() => { refetch() }, [refetch])

  return { data, loading, refetch }
}
