score:3

Accepted answer

The hook doesn't know the order of the array. So it might be ICampos | Handler or Handler | ICampos. You have two options here:

You can type the return array on the hook:

const useForm = (
  initialState: ICampos
): [ICampos, ({ target }: any) => void] => {
  const [values, setValues] = useState<ICampos>(initialState);

  const handleInputChange = ({ target }: any) => {
    setValues({
      ...values,
      [target.name]: target.value
    });
  };

  return [values, handleInputChange];
};

Or you could return an object instead of an array. I prefer this one since I don't like typing arrays.

import { useState } from "react";

interface ICampos {
  name: string;
  email: string;
  password: string;
}

const useForm = (initialState: ICampos) => {
  const [values, setValues] = useState<ICampos>(initialState);

  const handleInputChange = ({ target }: any) => {
    setValues({
      ...values,
      [target.name]: target.value
    });
  };

  return { values, handleInputChange };
};

export default useForm;
import React from "react";
import "./effects.css";
import useForm from "./useForm";

interface ICampos {
  name: string;
  email: string;
  password: string;
}

const FormWithCustomHook = () => {
  const { values, handleInputChange } = useForm({
    name: "",
    email: "",
    password: ""
  });

  const { name, email, password } = values;

  return (
    <>
      <h1> FormWithCustomHook </h1>
      <hr />

      <div className="form-group">
        <input
          type="text"
          name="name"
          className="form-control"
          placeholder="Tu nombre"
          autoComplete="off"
          value={name}
          onChange={handleInputChange}
        />
      </div>

      <div className="form-group">
        <input
          type="email"
          name="email"
          className="form-control"
          placeholder="email@ejemplo.com"
          autoComplete="off"
          value={email}
          onChange={handleInputChange}
        />
      </div>

      <div className="form-group">
        <input
          type="password"
          name="password"
          className="form-control"
          placeholder="*****"
          autoComplete="off"
          value={password}
          onChange={handleInputChange}
        />
      </div>
    </>
  );
};

export default FormWithCustomHook;

Related Query

More Query from same tag