File size: 632 Bytes
25732fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import { useState, useCallback } from 'react'
export const useApi = (apiFunc) => {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const execute = useCallback(async (...args) => {
try {
setLoading(true)
setError(null)
const response = await apiFunc(...args)
setData(response.data)
return response.data
} catch (err) {
setError(err.response?.data?.error || 'An error occurred')
throw err
} finally {
setLoading(false)
}
}, [apiFunc])
return { data, loading, error, execute }
} |