import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuthContext } from '../state/AuthContext'
import { callBubblesApi } from '../utility/api'
import { GET } from '../utility/constants/path'
export function useBubblesApi(params) {
const { verb = GET, path, payload, headers = {}, imperative = false } = params
const navigate = useNavigate()
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [result, setResult] = useState(null)
const valueRef = useRef([])
const { authData } = useAuthContext()
const tokenId = authData?.tokenId
const googleId = authData?.googleId
async function runImperative(params) {
const { verb = GET, path, payload, headers = {} } = params
const { data, err } = await callBubblesApi({
verb,
path,
payload,
headers: {
tokenId,
googleId,
...headers
}
})
return [data, err]
}
useEffect(async () => {
const [data, err] = await runImperative({
verb,
path,
payload,
headers: {
tokenId,
googleId,
...headers
}
})
if (err) {
setError(err)
} else {
setResult(data)
}
setLoading(false)
}, [])
useEffect(() => {
if (!authData) {
navigate('/', { replace: true })
} else if (imperative) {
valueRef.current = runImperative
} else {
valueRef.current = [result, error, loading]
}
})
return valueRef.current
}