简体   繁体   中英

How to specify a function as an optional parameter to a hook with a default value

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.

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();
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM