I'm trying to set up a custom hook to handle all api fetches in my project. I can make the call successfully, and store the data, but only on calls after the first one. I am pretty confident that the first call does not return anything because of race conditions and the nature of async.
Here is my hook:
import { useState, useEffect } from 'react'
import api from 'services/api'
const useHopServiceApi = () => {
const [data, setData] = useState([])
const [url, setUrl] = useState('')
const [body, setBody] = useState({})
const [isLoading, setIsLoading] = useState(false)
const [isError, setIsError] = useState(false)
useEffect(() => {
const fetchData = async () => {
setIsError(false)
setIsLoading(true)
try {
const result = await api.post(url, body)
setData(result.d)
} catch (error) {
setIsError(true)
}
setIsLoading(false)
}
if (url && body) {
fetchData()
}
}, [url, body])
return [{ data, isLoading, isError }, setUrl, setBody]
}
export default useHopServiceApi
and the component it is being called in:
const HomePage = (props) => {
const [{ data, isLoading, isError }, doFetch, setBody] = useHopServiceApi()
const handleClickSelectInterests = () => {
setBody({ count: 1 })
doFetch('/GetPopularCities')
console.log('data:', data)
}
}
When I click the button (to trigger the api call), data is logged out as an empty array, but on subsequent clicks, it is filled with the data.