I am trying to make an API call in a functional component which is a react-hook and based on the result, re-render the component's content. Here is the code:
Component which is calling the API-
function IntegrationDownshift() {
render(
<Paper square>
{setResults(inputValue).map(
(suggestion, index) =>
renderSuggestion({
suggestion,
index,
itemProps: getItemProps({
item:
suggestion.userFullName
}),
highlightedIndex,
selectedItem
})
)}
</Paper>
);
}
Here is the setResults
function:
function setResults(textInput) {
const [data, setData] = useState({ users: [] });
searchUser(textInput).then(result => {
useEffect(() => {
searchUser(textInput).then(result => {
setData(result.users);
});
}, []);
});
}
I'm trying to get the state's data and re-render my component based on the data.
Here searchUser
is in the action which calls the external API.
searchUser
is calling the action and fetching the data successfully, but I'm not sure why the state is getting updated - I got the below error -React Hook "useState" is called in function "setResults" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
I'm new to hooks and any help/pointers will be helpful.
React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function react recognize capitalized function name as a react function component, in your case for more, react aslo recognize function name begin with 'use' as custom hook,like
Therefore it is important to follow this semantics Since useState hook can only be used inside the functional component (or a custom hook) this is the reason why you are getting the error because react is not able to identify it as a user-defined component in the first place.
In order to react recognise the function as React component, need to Capitalized the name. Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.
The reason for this being that in the Rules of Hooks ESLint plugin, there is a check to see if a component or function name is valid: Checks if the node is a React component name. React component names must always start with a non-lowercase letter..
you need to put the first letter in uppercase setResults => SetResults
function SetResults(textInput) {
const [data, setData] = useState({ users: [] });
searchUser(textInput).then(result => {
useEffect(() => {
searchUser(textInput).then(result => {
setData(result.users);
});
}, []);
});
}
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