I was creating a function for my search bar but I receive this error:
Below is the function:
const HandleSearch = async (val) => {
useEffect(() => {
const fetchData = async () => {
const data = await db.collection('accounts').orderBy('date').get();
setAccounts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
fetchData();
}, []);
useEffect(() => {
setAccounts(
accounts.filter(
(account) =>
account.name.toLowerCase().includes(search.toLowerCase())
)
);
}, [search, accounts]);
}
CodePudding user response:
you might be using the hooks in a wrong way. as per rules of hooks, hooks can only be called from React function components and from a custom Hooks. Don’t call Hooks from regular JavaScript functions, inside loops, conditions, or nested functions.
CodePudding user response:
As the error message tells hooks can only be called inside function components.
Try removing the async
keyword preceding your component. This way React will understand it is a functional component and everything should work fine :)
At the moment it is not actually a component as components are supposed to return JSX
. By preceding it with the async
keyword it will implicitly return a Promise
.
You can read more about async
functions here. Promises are a pretty tricky concept and take time to fully understand.