I have been looking for a while and am not understanding how to get around this error.
I have a function that has a useEffect statement inside it. I need to call this function from within a loop(or map).
file1
export function useCustomFunction(year: number, month: number): any {
const customers = useAllCustomers();
const aggregator = useCustomerAggregator(year, month);
const [response, setResponse] = useState("" as string);
useEffect(() => {
console.log('i am doing stuff here')
setResponse('hello world')
}, [year, month, customers, aggregator]);
return response;
}
file2
import { useCustomFunction } from "file1";
export function EMDeltaDashboardPage(){
const dateCols = ["2022-10","2022-11","2022-12","2023-01","2023-02","2023-03","2023-04"]
useMemo(() => {
dateCols.forEach((element: any) => {
let year = Number(element.split("-")[0])
let month = Number(element.split("-")[1])
let budgets = useCustomFunction(year, month);
console.log(budgets)
},[dateCols])
In this case I am using file2 to call file1 useCustomFunction in a loop and budgets should be 'hello world' and should console.log 7 times.
However I am getting the following error message and am not sure how to get around this.
React Hook "useCustomFunction" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
CodePudding user response:
You cant. You can only call hooks in root component function. Instead of calling your hook each iteration you call it once and return a function which you then call:
const myCustomFn = myCustomHook();
dataCols.forEach((col) => {
// ...
myCustomFn(year, month));
});
CodePudding user response:
What you are trying to do breaks the rules of hooks: https://reactjs.org/docs/hooks-rules.html
Hooks need to be called at the top level of your component. Keep in mind that a hook can return a function. You could return a method that calculates the budget from useCustomFunction
.