Home > Net >  There is a way to call hooks conditionally in React?
There is a way to call hooks conditionally in React?

Time:11-19

I want to call a different hook according to a variable... this value comes from URL parameters and is dynamic, but hooks can't run conditionally according to Hook's rules:

Example

// this hook comes from react-router dom to get the URL params
const param = const { productType, accountId, statementId } = useParams();

// I need to run a hook that calls a different API according productType value
if (productType === 'someType') {
  return useHookOne(accountId, statementId)
} else if (productType === 'otherType') {
  return useHookTwo(accountId, statementId)
} else {
  return useHookThree(accountId, statementId)
}

CodePudding user response:

You need other components for each scenario. In each component, you can add a logic.

const param = const { productType, accountId, statementId } = useParams();

// I need to run a hook that calls a different API according productType value
if (productType === 'someType') {
  return <UseHookOne accountId={accountId} statementId={statementId} />
} else if (productType === 'otherType') {
  return <UseHookTwo accountId={accountId} statementId={statementId} />
} else {
  return <UseHookThree accountId={accountId} statementId={statementId} />
}

And then create 3 new components. Example with UseHookOne

import React from 'react'

const UseHookOne = (props) => {
  const data = useHookOne(props.accountId, props.statementId)
  return (<>Yay! Logic number 1 based on {data}</>)
}
export default UseHookOne

CodePudding user response:

Hooks can't be called into function or conditions

Use hook in the root and put condition for each Hook.

Can you predict the purpose of your code? I think the logical design of the code should just be approached from a different angle

EDIT with Exemple:

// this hook comes from react-router dom to get the URL params
const param = const { productType, accountId, statementId } = useParams();

// HERE: logical bloc
let apiRequest = new productRequestAPI();

if(prodType == "firstType"){
 apiQuest.adress = 'adress.api.com';
apiQuest.quest: 'firstRequest';
apiQuest.accountId ... etc
}
else if{
...
}

singleHook(oneSpecificRequestOfOneProduct){
//Call API with good params and return after

}

CodePudding user response:

you can make the useHookOne return a function that takes two arguments accountId and statementId .

const setHookOne = useHookOne()
const setHookTwo = useHookTwo()
const setHookThree = useHookThree()

if (productType === 'someType') {
  return setHookOne(accountId, statementId)
}else if (productType === 'otherType') {
  return setHookTwo(accountId, statementId)
} else {
  return setHookThree(accountId, statementId)
}
  • Related