I am trying to use below custom hook but it's not working as expected
CustomHook:
import { useEffect, useState } from 'react'
import { createAPIInstance } from '../utils/api'
import { getBaseUrl } from '../utils/functions'
const BASE_URL = getBaseUrl()
const useGetAPI = (endpoint) => {
const [data, setData] = useState([])
const api = createAPIInstance()
const getData = async () => {
const response = await api.get(`${BASE_URL}${endpoint}`)
setData(response.data)
}
useEffect(() => {
getData()
}, [])
return data
}
export {
useGetAPI
}
Here is the custom hook usage
app.js
function App() {
const [details, setDetails] = useState({})
useEffect(() => {
const fetchData = async () => {
const details = useGetAPI('/some-api-endpoint')
setDetails(details)
}
fetchData()
}, [])
return (
<div></div>
)
}
Error on chrome console:
Uncaught (in promise) Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
at invariant
React Version: 16.13.1 React-Dom Version: 16.13.1
For app.js
:
Why are you initialise a function in the same location ?
Example :
const fetchData = async () => {
const details = useGetAPI('/some-api-endpoint')
setDetails(details)
}
useEffect(async () => {
fetchData()
}, [])
You don't export default
your function.
Example :
export default function App() {
For CustomHook
:
You don't say as your function is using async
values.
Example :
const useGetAPI = async (endpoint) => {
useEffect(async () => {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.