import { useEffect, useState } from 'react'

export function useCloudQuery<T>(loader: () => Promise<T>, deps: unknown[], fallback: T) {
  const [data, setData] = useState<T>(fallback)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let alive = true
    setLoading(true)
    loader()
      .then(result => {
        if (alive) setData(result)
      })
      .finally(() => {
        if (alive) setLoading(false)
      })

    return () => {
      alive = false
    }
  }, deps)

  return { data, loading, setData }
}

