Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do to pass parameter to a custom hook

How do I pass a parameter from my return statement to the custom hook, I have created everything but just the method to pass the parameter to the custom hook is my problem.

  const {
      geodata: address,
      isPending,
      geoerror,}
    = useGeo(latitude, longitude);
  

You see useGeo that's the custom hook where I want to pass latitude and longitude (This works but I don't know to pass the parameter from the return statement)

So I tried method like this:

  const getAddApi = (latitude, longitude) => useGeo(latitude, longitude);

and in the return statement I tried this below but it didnt work I keep getting Error: 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:

<Text>{getAddApi(item.latitude, item.longitude).geodata}</Text>
like image 913
Nelson Adeyinka Avatar asked Oct 22 '25 10:10

Nelson Adeyinka


1 Answers

Custom hook is follows:

  • a function
  • call at least one build-in hook inside
  • used inside a function component (this is your error)

Suppose I design a custom hook like this,

  const useGeo = (latitude) => {
    const [state] = useState(latitude)
    return state
  }

It's a simple function with input latitude and return state. Now you can use it in a function component.

  const Title = () => {
    const s = useGeo(273)
    ...
  }

This is what a custom hook about. It's used mainly for algorithm refactoring. If you want to know more about input and output, just ask what you normally do for a function. The rest is the definition of the hooks that you have to meet which i listed above.

like image 156
windmaomao Avatar answered Oct 24 '25 23:10

windmaomao