Home > Software design >  How to specify a function as an optional parameter to a hook with a default value
How to specify a function as an optional parameter to a hook with a default value

Time:10-16

I am trying to write a custom hook in a react app using TypeScript that can take several, optional callback functions. However I am getting the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'onUpdate'). I write an interface like this:

interface UseMyHookProps {
  onConnect:() => void;
  onUpdate?:() => void;
  onDisconnect?:() => {};
}

And then my hook like this:

const useMyHook = ({ onConnect = () => {}, onUpdate = () => {}, onDisconnect = () => {} }: UseMyHookProps) => {
  ...
  // call the callback if defined.
  onUpdate();
};

finally I call the hook in a component function like this:

const MyComponent = () => {
  useMyHook();
  ...
};

I don't understand why I get this error. I say the callback is optional and provide a default argument of a void function that does nothing.

CodePudding user response:

The problem is that you are providing default values only for the attributes of the object, but not for the object itself which can still be undefined if you call the hook without parameters.

You can easily solve that by defaulting the hook's parameter to an empty object = {}

  const useMyHook = ({
    onConnect = () => {},
    onUpdate = () => {},
    onDisconnect = () => {},
  }: UseMyHookProps = {}) => { // <<<<
    // call the callback if defined.
    onUpdate();
  };

The version below is exatcly the same thing but more verbose, you can see that without defaulting params = {}, params would be undefined and the object destructuring below would fail

  const useMyHook = (params: UseMyHookProps = {}) => {
    const {
      onConnect = () => {},
      onUpdate = () => {},
      onDisconnect = () => {},
    } = params

    // call the callback if defined.
    onUpdate();
  };
  • Related