I want to use my custom hook inside a regular function as follows, but React won't let me do that. I wonder if my useUrl custom hook is not valid or there is something wrong with calling the hook.
const handleAddFormation = async () => {
console.log('add formation')
await useUrl('POST', 'http://localhost:1337/formations', newFormationList)
setNewFormationList([])
setModalOpen(false)
}
My custom hook:
export default function useUrl(method, url, args) {
const [data, setData] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
setLoading(true)
axios({
method,
url,
data: args
})
.then((res) => {
setData(res.data)
setLoading(false)
})
.catch((err) => {
console.log(err)
setLoading(false)
})
}, [])
if (!loading) return data
}
This gives me the following error:
React Hook "useUrl" is called in function "handleAddFormation" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter
From react doc,
Don’t call Hooks from regular JavaScript functions. Instead, you can:
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks
Also, you don't need use await for custom hook
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With