Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Custom hooks inside a handler function

Tags:

reactjs

Here with the given input i want to make a API request to get the cities data, but i am getting the error React Hook "useData" is called in function "handleCityInput" that is neither a React function component

//handle the city input
    const handleCityInput = (e) => {
        if (e.target.value.length < 3)
            return;
        
        //get the city data from the api
        const { data: citiesData } = useData("cities", { "country-id": selectedCountryISO2 });  //this line is giving the error
        setCitiesData(citiesData);
        

    }

How can i make it work?

like image 382
Bilal Akbar Avatar asked Mar 10 '26 17:03

Bilal Akbar


1 Answers

Instead of calling the hook inside the handler function, create the handler function inside the hook.

Like:

// -- your hook
const useData = function( X, Y, onDataLoaded ){

  return function loadData(){
    makeApiCall( X, Y ).then( onDataLoaded );
  };

};

// -- inside your component
const MyComponent = function(){
    const [ citiesData, setCitiesData ] = useState();

    const loadCityData = useData(
        "cities",
        { "country-id": selectedCountryISO2 },
        setCitiesData
    );

    const handleCityInput = (e) => {
        if( e.target.value.length < 3 ){ return; }
        loadCityData();
    };

    // ...
}
like image 160
kca Avatar answered Mar 12 '26 10:03

kca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!