Memory leak when submitting form
I have a hook that controls request to an endpoint and a form that makes a post when submitting and it's complaining that when submitting it's leaking memory, but I don't see where this is in the code.
ERROR:
FORM
const onSubmit = useCallback(
({ STRUCTURE_PARAMETER }: { STRUCTURE_PARAMETER: { [key: string]: string } }) => {
return QUOTATION_SERVICES_HOOK.askForQuote({
parameters: normalizeData(STRUCTURE_PARAMETER),
productInfoId: STRUCTURE_FORM_HOOK.dataId || '',
kindValue: switchMask,
});
},
[STRUCTURE_FORM_HOOK.dataId, switchMask]
);
HOOK
const useQuotation = () => {
const AXIOS_HOOK = useAxiosFetch();
const HISTORY_ROUTER_DOM_HOOK = useHistory();
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState<IQuotation[] | []>([]);
const [queryPageInit, setQueryPageInit] = useState(1);
const [queryPageEnd, setQueryPageEnd] = useState(0);
const hasData = useMemo(() => data.length > 0, [data]);
const dataLength = useMemo(() => data.length, [data]);
const isPaginationEnd = useMemo(() => queryPageInit === queryPageEnd, [queryPageInit, queryPageEnd]);
const fetchData = useCallback(async () => {
setIsLoading(true);
return AXIOS_HOOK.get<unknown, IQuotation[]>(`/Quotation?_page=${queryPageInit}&_limit=3`)
.then((quotation) => {
setData(quotation);
setQueryPageEnd(quotation.length); // CRIAR LÓGICA CORRETA A PARTIR DO BACKEND
setQueryPageInit(queryPageInit + 1); // CRIAR LÓGICA CORRETA A PARTIR DO BACKEND
})
.finally(() => setIsLoading(false));
}, [AXIOS_HOOK, queryPageInit]);
const askForQuote = useCallback(
async (parameter: IAskForQuote) => {
setIsLoading(true);
toast.info('Aguarde, Solicitando Cotação...');
return AXIOS_HOOK.post<unknown, IAskForQuote>(`/Quotation`, parameter)
.then(() => HISTORY_ROUTER_DOM_HOOK.push('/stored'))
.catch(() => toast.error('Ops, A cotação não pode ser solicitada!'))
.finally(() => setIsLoading(false));
},
[AXIOS_HOOK]
);
return {
isLoading,
isPaginationEnd,
data,
dataLength,
hasData,
fetchData,
askForQuote,
};
};
export default useQuotation;
I really can't see anything that could cause this leak, I'm following the documentation standards. Where is this leak actually located and what am I doing wrong?
The error is probably here:
return AXIOS_HOOK.post<unknown, IAskForQuote>(`/Quotation`, parameter)
.then(() => HISTORY_ROUTER_DOM_HOOK.push('/stored'))
.catch(() => toast.error('Ops, A cotação não pode ser solicitada!'))
.finally(() => setIsLoading(false));
You are calling history HISTORY_ROUTER_DOM_HOOK.push('/stored')
first
Then your component unmounts probably, because route was changed and you want to render another page.
And then you call .finally(() => setIsLoading(false));
which changes the state of the hook which was already unmounted.
Maybe you have other similar places, look for similar situations in your code.