Я пытаюсь использовать реакцию-кхайс-форма с контекстом React, но форма не ведет себя как предполагаемое. Состояния ошибки отправки не запускаются. >
Значения, такие как Isdirty, Issubmitccessful не изменяются от начального состояния. потреблял его внутри компонента, где создается форма, и все работает просто отлично.
Я хотел знать, знает ли кто -нибудь о том, почему это так? Разве мы не можем использовать Реакцию-Кюунс в боковой поставщике контекста? JS PrettyPrint-Override ">import { zodResolver } from '@hookform/resolvers/zod';
import { createContext, ReactNode, useContext } from 'react';
import { useForm, UseFormReturn } from 'react-hook-form';
import { z } from 'zod';
import { CompanyTypeEnum } from '@/types/buyer.type';
import { CountrySchema, PhoneSchema } from '@/types/common.type';
type BuyerFormContext = UseFormReturn;
const BuyerFormContext = createContext(undefined);
const BuyerFormSchema = z.object({
id: z.string().uuid().optional(),
companyName: z.string().min(1),
companyType: CompanyTypeEnum,
companyPhone: PhoneSchema,
streetLine1: z.string().min(1),
streetLine2: z.string().optional(),
city: z.string().min(1),
stateOrRegion: z.string().min(1),
postalCode: z.string().min(1),
country: CountrySchema,
website: z.string().min(1),
defaultCurrency: z.string(),
contactName: z.string().min(1),
contactPosition: z.string().min(1),
contactPhone: PhoneSchema,
contactEmail: z.string().email(),
});
export type BuyerForm = z.infer;
export const BuyerFormProvider = ({
children,
defaultValues,
}: {
children: ReactNode;
defaultValues?: BuyerForm;
}) => {
const form = useForm({
resolver: zodResolver(BuyerFormSchema),
mode: 'onSubmit',
defaultValues: formDefault,
});
return {children};
};
export const useBuyerForm = () => {
const context = useContext(BuyerFormContext);
if (context === undefined) {
throw new Error('useBuyerForm must be used within a BuyerFormProvider');
}
return context;
};
< /code>
Мое использование, как ниже < /p>
import { Loader2 } from 'lucide-react';
import { SubmitHandler } from 'react-hook-form';
import { useBlocker } from 'react-router-dom';
import { CustomSelect as CompanyTypeSelect } from '@/components/custom-select';
import { CustomSelect as ContactPositionSelect } from '@/components/custom-select';
import { Button } from '@/components/ui/button';
import { CountryDropdown } from '@/components/ui/country-dropdown';
import { CurrencySelect } from '@/components/ui/currency-select';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { PhoneInput } from '@/components/ui/phone-input';
import { Separator } from '@/components/ui/separator';
import { type BuyerForm, useBuyerForm } from '@/context/buyer-form-context';
import { CURRENCIES } from '@/service/types';
import { COMPANY_TYPES } from '@/types/buyer.type';
import { CONTACT_POSITIONS, Country } from '@/types/common.type';
const BuyerForm = (props: {
onCancel: () => void;
onSubmit: SubmitHandler;
formTitle?: string;
submitBtnText?: string;
isFormLoading?: boolean;
isEdit?: boolean;
}) => {
const {
onCancel,
onSubmit,
formTitle = 'Edit Buyer',
submitBtnText = 'Save Changes',
isFormLoading = false,
isEdit = false,
} = props;
const form = useBuyerForm(); // Assuming you are using useForm from react-hook-form
const {
formState: { isDirty, isSubmitSuccessful },
} = form;
useBlocker(({ currentLocation, nextLocation }) => {
if (!isSubmitSuccessful && isDirty && currentLocation.pathname !== nextLocation.pathname) {
return !window.confirm('You have unsaved changes. Are you sure you want to leave?');
}
return false;
});
const onCountryChange = (country: Country) => {
const formValues = form.getValues();
if (!isEdit) {
if (!form.getFieldState('defaultCurrency').isTouched || formValues.defaultCurrency === '') {
const countryCurrency = country.currencies[0];
if ((CURRENCIES as string[]).includes(countryCurrency)) {
form.setValue('defaultCurrency', countryCurrency);
}
}
if (!form.getFieldState('companyPhone').isTouched || formValues.companyPhone.phone === '') {
form.setValue('companyPhone', {
phone: country.countryCallingCodes[0],
country: country,
});
}
}
};
return (
{formTitle}
(
Company Name
)}
/>
(
Company Type
)}
/>
(
Company Phone
{
field.onChange({
phone: e.target.value.phone,
country: e.target.value.country,
});
}}
value={field.value.phone}
placeholder='Enter your number'
defaultCountry={field.value.country?.alpha2}
className='h-10'
/>
Include country code (e.g. +44)
)}
/>
(
Website
)}
/>
Address
(
Street Line 1
)}
/>
(
Street Line 2 (optional)
)}
/>
(
Postal Code
)}
/>
(
City
)}
/>
(
State/Region
)}
/>
(
Country
{
field.onChange(country);
onCountryChange(country);
}}
ref={field.ref}
/>
)}
/>
Contact Person
(
Name
)}
/>
(
Position
)}
/>
(
Email
)}
/>
(
Phone
{
const countryCode = country.countryCallingCodes[0];
const formattedCode = countryCode.startsWith('+')
? countryCode
: `+${countryCode}`;
form.setValue(`contactPhone`, {
phone: formattedCode,
country: country,
});
}}
defaultValue={field.value.country?.alpha3}
inline
/>
{
field.onChange({
phone: e.target.value.phone,
country: e.target.value.country,
});
}}
value={field.value.phone}
placeholder='Enter your number'
defaultCountry={field.value.country?.alpha2}
inline
/>
)}
/>
(
Payment Currency
)}
/>
Cancel
{isFormLoading && }
{submitBtnText}
);
};
export default BuyerForm;
Подробнее здесь: https://stackoverflow.com/questions/794 ... ct-context
Как использовать реакцию-крючок с контекстом React? ⇐ Javascript
Форум по Javascript
-
Anonymous
1738405836
Anonymous
Я пытаюсь использовать реакцию-кхайс-форма с контекстом React, но форма не ведет себя как предполагаемое. Состояния ошибки отправки не запускаются. >
Значения, такие как Isdirty, Issubmitccessful не изменяются от начального состояния. потреблял его внутри компонента, где создается форма, и все работает просто отлично.
Я хотел знать, знает ли кто -нибудь о том, почему это так? Разве мы не можем использовать Реакцию-Кюунс в боковой поставщике контекста? JS PrettyPrint-Override ">import { zodResolver } from '@hookform/resolvers/zod';
import { createContext, ReactNode, useContext } from 'react';
import { useForm, UseFormReturn } from 'react-hook-form';
import { z } from 'zod';
import { CompanyTypeEnum } from '@/types/buyer.type';
import { CountrySchema, PhoneSchema } from '@/types/common.type';
type BuyerFormContext = UseFormReturn;
const BuyerFormContext = createContext(undefined);
const BuyerFormSchema = z.object({
id: z.string().uuid().optional(),
companyName: z.string().min(1),
companyType: CompanyTypeEnum,
companyPhone: PhoneSchema,
streetLine1: z.string().min(1),
streetLine2: z.string().optional(),
city: z.string().min(1),
stateOrRegion: z.string().min(1),
postalCode: z.string().min(1),
country: CountrySchema,
website: z.string().min(1),
defaultCurrency: z.string(),
contactName: z.string().min(1),
contactPosition: z.string().min(1),
contactPhone: PhoneSchema,
contactEmail: z.string().email(),
});
export type BuyerForm = z.infer;
export const BuyerFormProvider = ({
children,
defaultValues,
}: {
children: ReactNode;
defaultValues?: BuyerForm;
}) => {
const form = useForm({
resolver: zodResolver(BuyerFormSchema),
mode: 'onSubmit',
defaultValues: formDefault,
});
return {children};
};
export const useBuyerForm = () => {
const context = useContext(BuyerFormContext);
if (context === undefined) {
throw new Error('useBuyerForm must be used within a BuyerFormProvider');
}
return context;
};
< /code>
Мое использование, как ниже < /p>
import { Loader2 } from 'lucide-react';
import { SubmitHandler } from 'react-hook-form';
import { useBlocker } from 'react-router-dom';
import { CustomSelect as CompanyTypeSelect } from '@/components/custom-select';
import { CustomSelect as ContactPositionSelect } from '@/components/custom-select';
import { Button } from '@/components/ui/button';
import { CountryDropdown } from '@/components/ui/country-dropdown';
import { CurrencySelect } from '@/components/ui/currency-select';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { PhoneInput } from '@/components/ui/phone-input';
import { Separator } from '@/components/ui/separator';
import { type BuyerForm, useBuyerForm } from '@/context/buyer-form-context';
import { CURRENCIES } from '@/service/types';
import { COMPANY_TYPES } from '@/types/buyer.type';
import { CONTACT_POSITIONS, Country } from '@/types/common.type';
const BuyerForm = (props: {
onCancel: () => void;
onSubmit: SubmitHandler;
formTitle?: string;
submitBtnText?: string;
isFormLoading?: boolean;
isEdit?: boolean;
}) => {
const {
onCancel,
onSubmit,
formTitle = 'Edit Buyer',
submitBtnText = 'Save Changes',
isFormLoading = false,
isEdit = false,
} = props;
const form = useBuyerForm(); // Assuming you are using useForm from react-hook-form
const {
formState: { isDirty, isSubmitSuccessful },
} = form;
useBlocker(({ currentLocation, nextLocation }) => {
if (!isSubmitSuccessful && isDirty && currentLocation.pathname !== nextLocation.pathname) {
return !window.confirm('You have unsaved changes. Are you sure you want to leave?');
}
return false;
});
const onCountryChange = (country: Country) => {
const formValues = form.getValues();
if (!isEdit) {
if (!form.getFieldState('defaultCurrency').isTouched || formValues.defaultCurrency === '') {
const countryCurrency = country.currencies[0];
if ((CURRENCIES as string[]).includes(countryCurrency)) {
form.setValue('defaultCurrency', countryCurrency);
}
}
if (!form.getFieldState('companyPhone').isTouched || formValues.companyPhone.phone === '') {
form.setValue('companyPhone', {
phone: country.countryCallingCodes[0],
country: country,
});
}
}
};
return (
{formTitle}
(
Company Name
)}
/>
(
Company Type
)}
/>
(
Company Phone
{
field.onChange({
phone: e.target.value.phone,
country: e.target.value.country,
});
}}
value={field.value.phone}
placeholder='Enter your number'
defaultCountry={field.value.country?.alpha2}
className='h-10'
/>
Include country code (e.g. +44)
)}
/>
(
Website
)}
/>
Address
(
Street Line 1
)}
/>
(
Street Line 2 (optional)
)}
/>
(
Postal Code
)}
/>
(
City
)}
/>
(
State/Region
)}
/>
(
Country
{
field.onChange(country);
onCountryChange(country);
}}
ref={field.ref}
/>
)}
/>
Contact Person
(
Name
)}
/>
(
Position
)}
/>
(
)}
/>
(
Phone
{
const countryCode = country.countryCallingCodes[0];
const formattedCode = countryCode.startsWith('+')
? countryCode
: `+${countryCode}`;
form.setValue(`contactPhone`, {
phone: formattedCode,
country: country,
});
}}
defaultValue={field.value.country?.alpha3}
inline
/>
{
field.onChange({
phone: e.target.value.phone,
country: e.target.value.country,
});
}}
value={field.value.phone}
placeholder='Enter your number'
defaultCountry={field.value.country?.alpha2}
inline
/>
)}
/>
(
Payment Currency
)}
/>
Cancel
{isFormLoading && }
{submitBtnText}
);
};
export default BuyerForm;
Подробнее здесь: [url]https://stackoverflow.com/questions/79404792/how-to-use-react-hook-form-with-react-context[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия