4

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;
7
  • 2
    Typo: You got the order of the two elements in your array reversed. Commented Jan 10, 2022 at 10:37
  • 1
    off topic: handleLazyLoad={handleLazyLoad} is better Commented Jan 10, 2022 at 10:38
  • Nice one, I didn't realise the order mattered or think of switching it Commented Jan 10, 2022 at 10:38
  • 1
    is does when its an array, if you had of returned an object, it wouldnt Commented Jan 10, 2022 at 10:40
  • @Thomas, depends, sometimes you dont want the args to passed through to the function automatically Commented Jan 10, 2022 at 10:41

2 Answers 2

6

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,
  );
Sign up to request clarification or add additional context in comments.

Comments

1

The order matters when you destructure on array Try

const [totalShownInvoices,handleLazyLoad] = useLoadInvoices(
    1,
    totalInvoices,
  );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.