import { useEffect, useState } from 'react'

/**
 * It takes a function that returns a promise, and returns a tuple of three values: the data, a boolean
 * indicating whether the data is loading, and an error
 * @param fetch - A function that returns a promise.
 * @returns The data, loading and error states.
 */
const useFetch = (fetch) => {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(Boolean(fetch))
  const [error, setError] = useState(null)

  useEffect(() => {
    let isMounted = true

    const fetchData = async () => {
      try {
        const data = await fetch?.()
        if (isMounted) {
          setData(data)
          setLoading(false)
          setError(null)
        }
      } catch (error) {
        isMounted && setError(error)
        console.error(error)
      }
    }

    isMounted && fetch && fetchData()
    return () => (isMounted = false)
  }, [fetch])

  return [data, loading, error]
}

export default useFetch
