Home > Software engineering >  getting an Uncaught TypeError: lake is not a function
getting an Uncaught TypeError: lake is not a function

Time:04-27

Edited to add the whole hook

The below code is inside a custom hook. When I call the custom hook I get an unCaught TypeError telling me the arrow function is not a function. Could someone explain what I did wrong and would be the correct way to handle this?

const useHook = ({
  Id,
}) => {
let Data = {};
arrowFunction(Id); //calling the arrow function a couple lines below

  const arrowFunction = (Id) => {
    const lakeHook = useLake();
    if (Id) Data = lakeHook.getReference(Id);
    if (Data.active){
      console.log('data', Data);
      return Data;
    }
  }
}

CodePudding user response:

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

Docs: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting?retiredLocale=it

You are trying to read the function stored in the const arrowFunction but that's not something allowed due to how it works hoisting in javascript with const variables. So what you need to do to call the function before the declaration is declaring it with the proper keywoard:

arrowFunction(Id);
function arrowFunction(Id){
 //logic
}

Or alternatively call the function after creating it

const arrowFunction = (Id) => {
 //logic
}
arrowFunction(Id);

CodePudding user response:

 const useHook = ({
      Id,
    }) => {
    const lakeHook = useLake(); // hooks should be called only on top level
    let Data = {};
    const arrowFunction = (Id) => {
        if (Id) Data = lakeHook.getReference(Id);
        if (Data.active){
          console.log('data', Data);
          return Data;
        }
      }
    arrowFunction(Id); //calling the arrow function a couple lines below
    return ??? // declare return statement (optional);
    }

  1. Function Expression are not hoisted. Use Function Declaration instead.
  2. lakeHook should be moved to a top level according to rules of hooks.
  3. You probably want your custom useHook return something so declare return statement. (optional)
  • Related