Jkaram
Jkaram

Reputation: 923

Custom useInput hook and typescript error

I am new to typescript.

I made a custom useInput hook:

export const useInput = (initialValue = "") => {
  const [value, setValue] = useState(initialValue);

  const onChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => setValue(e.currentTarget.value),
    []
  );

  return [value, onChange, setValue];
};

I am referencing this hook in a form like so

  const [deviceInput, bindDeviceInput, setDeviceInput] = useInput();
  const assignUserId = (deviceId: string) => {
    setDeviceInput(deviceId);
  };

value and onChange work, setValue gives me this error

> This expression is not callable.   Not all constituents of type
> 'string | Dispatch<SetStateAction<string>> | ((e:
> ChangeEvent<HTMLInputElement>) => void)' are callable.
>     Type 'string' has no call signatures.

This is one typescript error I cannot figure out.

Upvotes: 1

Views: 700

Answers (1)

Adam Jenkins
Adam Jenkins

Reputation: 55643

You need to be explicit about what you are returning. Typescript just thinks you are returning an array where each element could be any of the other ones. I'm not sure why, I feel like this could be a bug in typescript, haven't checked.

Do this:

type useInputHook<T> = [T, (val: T) => void, Dispatch<SetStateAction<T>>];

export const useInput = <T>(initialValue: T = ""): useInputHook<T> => {
  const [value, setValue] = useState(initialValue);

  const onChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => setValue(e.currentTarget.value),
    []
  );

  return [value, onChange, setValue];
};

Upvotes: 1

Related Questions