'calling a specific function to do a task inside React onClick Callback function
I am trying to do a specific task whenever an item is called. But this is compromising DRY principal so I tried to finish the work by using a function and got a React error! then tried to do it with CustomHooks but got the same error!! is there any way to avoid code code repetition
React Hook "useDeleteInventory" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
callback function
onClick={() => useDeleteInventory(
item._id,
myInventories,
setMyInventories
)
}
CustomHook -
import axios from "axios";
const useDeleteInventory = async (id, inventories, setInventories) => {
const url = `http://localhost:5000/inventories/${id}`;
const proceed = window.confirm("Are you sure?");
if (proceed) {
await axios.delete(url);
const remainingInventories = inventories.filter(
(inventory) => inventory._id !== id
);
setInventories(remainingInventories);
}
}
export default useDeleteInventory
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
