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?
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();
};
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With