Home > Blockchain >  Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a fun
Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a fun

Time:10-03

I am having trouble using custom hooks inside the useEffect function. I have googled for hours and was unable to find a fix for this issue. Here is the chunk of code I am having an issue with:

  const [ stripeApiKey, setStripeApiKey ] = useState('');

  useEffect(() => {
    store.dispatch(loadUser())

    async function getStripeApiKey() {
      const { data } = await axios.get('/api/v1/stripeapi');
      setStripeApiKey(data.stripeApiKey)
    }

    getStripeApiKey();
  }, [])

I am trying to use the custom hook to set Stripe API key which I want to use later in the return function. But I am getting the following error: Invalid Hook Call Error

CodePudding user response:

You can simply fix this by using useDispatch hooks:

First, import it:

import {useDispatch} from 'react-redux';

Second, inside of your component:

// rest of codes
const [ stripeApiKey, setStripeApiKey ] = useState('');

const dispatch = useDispatch()
// rest of codes

Now, use your dispatch method in useEffect:

  useEffect(() => {
    dispatch(loadUser()) // -----> replaced 

    async function getStripeApiKey() {
       try{
          const { data } = await axios.get('/api/v1/stripeapi');
          setStripeApiKey(data.stripeApiKey)
       } catch (e) {
          console.log(e)
          // you can do anything here
       }
    }

    getStripeApiKey();
  }, [])

Note: always use try/catch block with your async/await implementation especially when working with API calls.

CodePudding user response:

you can give a read to react docs https://reactjs.org/docs/hooks-rules.html which states Don’t call Hooks inside loops, conditions, or nested functions

  • Related