Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function called from a react custom hook returns 'is not a function'

When I try and call a function from my custom hook I get back an error when the screen loads saying 'handleLazyLoad' is not a function. Im not sure why React cant figure out that the handleLazyLoad is a function, I am thinking I am possible exporting it or calling it incorrectly.

Custom hook:

import { useState } from 'react';

const useLoadInvoices = (initialPageValue, totalInvoices) => {
  const [currentPage, setCurrentPage] = useState(initialPageValue);

  const pageSize = 30;

  const handleLazyLoad = () => {
    if (currentPage * pageSize < totalInvoices) setCurrentPage(currentPage + 1);
  };

  const totalShownInvoices = currentPage * pageSize > totalInvoices ? totalInvoices : currentPage * pageSize;

  return [totalShownInvoices, handleLazyLoad];
};

export default useLoadInvoices;

Invoice Screen Component:

import React from 'react';
import useLazyLoad from './hooks/useLazyLoad';

const InvoicesScreen = () => {
  const [invoices, setInvoices] = useState(null);
  const [totalInvoices, setTotalInvoices] = useState(null);
  const [handleLazyLoad, totalShownInvoices] = useLoadInvoices(1, totalInvoices);

  handleLazyLoad();

  return (
    <AccountPageList
      type="invoices"
      handleLazyLoad={() => handleLazyLoad()}
      start={1}
      finish={totalShownInvoices}
      total={totalInvoices}
      items={invoices}
    />
  );
};

export default InvoicesScreen;
like image 291
walker1 Avatar asked Sep 15 '25 19:09

walker1


1 Answers

You are returning an Array from your custom hook, so when destructuring the custom hook the order matters. To Avoid such problems you can change this part in your custom hook from:

return [totalShownInvoices, handleLazyLoad];

to:

return {totalShownInvoices, handleLazyLoad};

Then you can destructure it as follows and the order wouldnt matter:

const {handleLazyLoad, totalShownInvoices} = useLoadInvoices(
    1,
    totalInvoices,
  );
like image 168
Michael Avatar answered Sep 17 '25 08:09

Michael