8

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
3
  • 1
    As the error message states, you can use custom hooks only in 2 cases , custom hooks inside another custom hook or inside the functional component . Your handleAddFormation is neither of those . Commented Aug 29, 2021 at 8:47
  • From what is understand you are trying to mimic something like this react-query.tanstack.com/guides/mutations . You need to make your custom hook to return a function which will run at the later point of time when you are doing create/update/delete operations . Commented Aug 29, 2021 at 8:51
  • @Shyam Yes, but how to point to a specific function within the custom hook file? For example I'd like to have one function for create and another one for delete. Commented Aug 29, 2021 at 9:54

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

What should my code be in order to make this work?
move useUrl from your handler, and use value that was returned in your handler
Makes sense, but I'd like to only make a post request in my handler, not everytime the components mounts.
in this case you should create a custom hook, which will return useCallback instead of value, and invoke it in your handler const getResource = useResourceCallback() const handleAddFormation = async () => { const data = await getResource() }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.