Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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,
  );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading