I created a custom hook usePostCategory
to post a new category. The hook is called from another component, but when I try to do it, I receive an error:
" Invalid hook call. Hooks can only be called inside of the body of a function component".
Just wondering if I call the hook in the right way, since I get confuse because it accepts parameters and also return something
usePostCategory hook:
export const usePostCategory = async (categoryName, id, catId) => {
const data = { name: categoryName, a_id: id, cat_id: catId };
const [message, setMessagge] = useState();
try {
const response = await axios.post(`url`, data, {
headers: {...
},
});
if (response.status === 201) {
}
} catch (err) {
}
return { message };
};
This is the parent component where I call the hook:
import {usePostCategory } from "../../../api/bagAPI/fetchBag";
function Foo(value, id, catID) {
const message = usePostCategory(value, id, catID);
return message;
}
const handleAddCategory = () => {
setOpenAddCategory(true);
};
<Fab
onClick={handleAddCategory}
text="Category"
icon={<AddIcon/>}>
</Fab>
<CustomFormDialog
title="Add category"
onClick={Foo}
id={id}
editCatId={currentCatId}
/>
**and also my dialog:**
const CustomFormDialog = ({ open, onClose, title, id, onClick, editCatId }) => {}
<Button
onClick={() => {
onClick(value, id, editCatId);
}}>
I have been trying different way, but I always get the same error:
const { message } = usePostCategory();
<CustomFormDialog
title="Add category"
onClick={usePostCategory}
id={id}
editCatId={currentCatId}
/>