Search code examples
reactjstypescriptreact-typescript

Default prop error: Expected 1 arguments, but got 0


I created this utility to detect mobile using matchMedia.

I created a prop to manually adjust the breakpoint if needed. I defined the breakpoint prop as optional and gave a default value in the function.

For some reason I'm required to pass an empty object though when using the util?

OtherCompnent.tsx:
const { isMobile } = DetectMobile({});

If I remove the empty object I get the error:

Expected 1 arguments, but got 0

I'm fairly new to typescript and I'm not entirely sure what I'm doing wrong, I feel like I should not need to pass the empty object and it should pick up on the default value for the breakpoint prop?

Here's the util:

import { useEffect, useState, useMemo } from "react";

type DetectMobileProps = {
  breakpoint?: string;
};

export function DetectMobile({ breakpoint = "768px" }: DetectMobileProps) {
  const [isMobileDevice, setIsMobile] = useState(false);

  useEffect(() => {
    const mediaWatcher = window.matchMedia(`(max-width: ${breakpoint})`);
    setIsMobile(mediaWatcher.matches);

    function updateIsMobile(event) {
      setIsMobile(event.matches);
    }

    if (mediaWatcher.addEventListener) {
      mediaWatcher.addEventListener("change", updateIsMobile);
    }
  }, []);

  const isMobile = useMemo(() => {
    return isMobileDevice;
  }, [isMobileDevice]);

  return {
    isMobile
  };
}

Any advice/help?


Solution

  • Your DetectMobile function requires a parameter because the props themselves are not optional.

    If you wanted a truly optional prop, you'd have to do something like this:

    export function DetectMobile(prop?: string) => {
       // rest of code
       // adjust "breakpoint" to "prop.breakpoint"
    }