Reputation: 105
I need to re-fetching data if i click some button, but when i call hook inside click handler i get following error
const Menus = ({ menus, title }) => {
const handleClick = () => {
const { data: cartItems } = useFetch(API_URL + 'cart');
}
}
src\components\Menus.js | Line 26:13: React Hook "useFetch" is called in function "handleMenu" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter react-hooks/rules-of-hooks
Upvotes: 1
Views: 3022
Reputation: 102267
React hooks can't be used inside a pure JavaScript function. It will break the rules of hooks. Hooks can only be used in React function components. A function returning ReactElement will be treated as a React function component instead of a normal function in JS.
You should return the data and a data fetch function in the useFetch
hook. So that you can use the data fetch function later.
E.g.
import React from 'react';
import { useCallback, useEffect, useState } from 'react';
const API_URL = 'http://localhost:8080/api/';
const api = {
async getCartItems() {
return ['apple', 'banana'];
},
};
function useFetch(url: string) {
const [cartItems, setCartItems] = useState<string[]>([]);
// fetch data later use this function.
const getCartItems = useCallback(() => {
return api.getCartItems().then((res) => {
setCartItems(res);
});
}, [url]);
// fetch data when component mount
useEffect(() => {
getCartItems();
}, [url]);
return { data: cartItems, getCartItems };
}
const Menus = () => {
const { data: cartItems, getCartItems } = useFetch(API_URL + 'cart');
const handleClick = () => {
getCartItems();
};
return (
<div onClick={handleClick}>
<ul>
{cartItems.map((item, i) => {
return <li key={i}>{item}</li>;
})}
</ul>
</div>
);
};
Upvotes: 2
Reputation: 63
As the error mentions, the issue violates the rules of hooks (react-hooks/rules-of-hooks
)
More information can be found here:
https://reactjs.org/docs/hooks-rules.html
You can only use hooks in the top level of functional components but the handleClick()
function would put the hook at the second level rather than the top level.
Upvotes: 1