Comments (2)
@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.
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)
- Question : How to make drawer globally? HOT 3
- Where must I put these files? [React, React Native] HOT 1
- Why we need to use number for createdAt in BaseEntity class HOT 3
- CRA is unmaintained HOT 3
- Avoid barrel files
- Update react-router usage
- [minor]: Typo in ~/README.md HOT 2
- Missing Link/Example in Global Store Management
- Some links are Not found HOT 1
- Auth flow does not work with new cookies
- Logo/Mascot idea :) HOT 1
- .env validation on build
- Not sure the Validation Example Code link is going to the right place HOT 1
- rimraf and glob are deprecated
- Documentation discrepancy HOT 1
- API issue (API seems to be down).
- [SUGGESTION] Styles Folder
- [QUESTION] - Barrel file performance HOT 2
- Remove duplicate text about 'handling user data' in the security doc
- Switch to "auth/login" after logged HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from bulletproof-react.