Giter VIP home page Giter VIP logo

Comments (2)

shobhitk8055 avatar shobhitk8055 commented on September 17, 2024

@yyykkkyyy There is one solution to it using iife

export const LoginForm = ({ onSuccess }: LoginFormProps) => {
  const { login, isLoggingIn } = useAuth();

  var setNewValue;

  const handleClick = () => {
    setNewValue('email', 'abc');
  }

  return (
    <div>
      <Form<LoginValues, typeof schema>
        onSubmit={async (values) => {
          await login(values);
          onSuccess();
        }}
        schema={schema}
      >
        {({ register, formState, setValue }) => (
          <>
            {(() => {
              setNewValue = setValue;
            })()}
            <Button onClick={handleClick}>Change Value</Button>
            <InputField
              type="email"
              label="Email Address"
              error={formState.errors['email']}
              registration={register('email')}
            />
            <div>
              <Button isLoading={isLoggingIn} type="submit" className="w-full">
                Log in
              </Button>
            </div>
          </>
        )}
      </Form>
    </div>
  );
};

Similarly you can use other function which are available in useForm() hook

from bulletproof-react.

shobhitk8055 avatar shobhitk8055 commented on September 17, 2024

There is one more solution, but it is pretty big one. First you have to change the Form.tsx component to this

import clsx from 'clsx';
import * as React from 'react';
import { UseFormReturn, SubmitHandler, UseFormProps, FieldValues } from 'react-hook-form';

type FormProps<TFormValues extends FieldValues> = {
  className?: string;
  onSubmit: SubmitHandler<TFormValues>;
  children: React.ReactNode;
  options?: UseFormProps<TFormValues>;
  id?: string;
  methods: UseFormReturn<TFormValues>;
};

const Form = <
  TFormValues extends Record<string, unknown> = Record<string, unknown>>({
  onSubmit,
  children,
  className,
  id,
  methods
}: FormProps<TFormValues>) => {
  return (
    <form
      className={clsx('', className)}
      onSubmit={methods.handleSubmit(onSubmit)}
      id={id}
    >
      {children}
    </form>
  );
};

export default Form;

Then create a hook named useHookForm.ts

import { zodResolver } from "@hookform/resolvers/zod";
import { Path, PathValue, UseFormProps, useForm } from "react-hook-form";
import { ZodType, ZodTypeDef } from "zod";

export const useHookForm = <
  TFormValues extends Record<string, unknown> = Record<string, unknown>,
  Schema extends ZodType<unknown, ZodTypeDef, unknown> = ZodType<
    unknown,
    ZodTypeDef,
    unknown
  >
>(
  schema: Schema,
  options?: UseFormProps<TFormValues>,
) => {
  const methods = useForm<TFormValues>({
    ...options,
    resolver: schema && zodResolver(schema),
  });

  const setValues = (valuesToSet: Partial<TFormValues>) => {
    Object.keys(valuesToSet).forEach((fieldName) => {
      methods.setValue(
        fieldName as Path<TFormValues>,
        valuesToSet[fieldName] as PathValue<TFormValues, Path<TFormValues>>
      );
    });
  };
  return { methods, setValues };
};

Then in Login.tsx you can do like this

export const LoginForm = ({ onSuccess }: LoginFormProps) => {
  const { methods } = useHookForm<LoginValues, typeof schema>(schema);
  const { formState, control, setValue } = methods;

  const login = useLogin();
  const navigate = useNavigate();
  const { animate, callAfterAnimateFn } = useAnimateFn();

  const handleClick = () => {
    setValue('email', 'abc');
  }

  return (
    <AnimatePresence>
      {animate && (
        <motion.div {...animations}>
          <div className="card p-4 mt-4 mx-4">
            <Form<LoginValues>
              onSubmit={async (values) => {
                console.log(values);
                // values;
                // onSuccess();
                login.mutate(values, { onSuccess });
              }}
              methods={methods}
            >
              <InputField
                control={control}
                type={TextFieldTextType.TEXT}
                title="Email Address"
                error={formState.errors["email"]}
                name="email"
              />
              <InputField
                control={control}
                type={TextFieldTextType.PASSWORD}
                title="Password"
                error={formState.errors["password"]}
                name="password"
                wrapperClassName="mt-3"
              />
              <div className="d-flex justify-content-center">
                <Button
                  leftIcon={Locked}
                  isLoading={login.isLoading}
                  type="submit"
                  className="w-100 mt-3"
                >
                  Log In
                </Button>
              </div>
            </Form>
            <Link
              to="#"
              onClick={callAfterAnimateFn(() => navigate("/auth/forget"))}
              className="forget-link"
            >
              Forget Password
            </Link>
          </div>
          <p className="text-center mt-2">
            Don't have an account?{" "}
            <Link
              to="#"
              onClick={callAfterAnimateFn(() => navigate("/auth/register"))}
              className="forget-link"
            >
              Sign Up
            </Link>
          </p>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

@alan2207 If you like this solution, I can change it in the whole app, and then I can raise a pr for it ?

from bulletproof-react.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.