Home > database >  Error initialising react hook with a function call
Error initialising react hook with a function call

Time:11-18

Why this code doesn't work:

let [kgFormValues, setKgFormValues] = useState<KgFormValues>(getKgFormValues());

Error: ReferenceError: Cannot access 'kgFormValues' before initialization

But when removing the parentheses works:

let [kgFormValues, setKgFormValues] = useState<KgFormValues>(getKgFormValues);

function getKgFormValues() {
    return {
      ...
    };
}

CodePudding user response:

In order to get this to work, you must call the function after it's declared.

For example:

function getKgFormValues() {
    return {
      ...
    };
}

// now you can use it, as such:
let [kgFormValues, setKgFormValues] = useState<KgFormValues>(getKgFormValues);

  • Related