React Hook "useState" is called in function "setResults" which is neither a React function component or a custom React Hook function

beta programmers picture beta programmers · Jun 5, 2019 · Viewed 15.9k times · Source

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.

  1. The 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

  1. As a second alternate, I'm trying to return the values from the searchUser and access it in the below function, still, no use

I'm new to hooks and any help/pointers will be helpful.

Answer

ramsesls picture ramsesls · Sep 27, 2019

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);
            });
        }, []);
    });
}