admin管理员组

文章数量:1122846

I am creating a React Native Expo app and I am having problems creating a form with react-hook-form and zod for validation.

For simplicity I will only provide the part of code related to this error (there are too many lines of code for the other fields that are now useless).

This is the simplified zod schema:

export const createEventSchema = z.object({
    rates: z.array(z.object({
        label: z.string().or(z.literal("")).optional(),
        cost: z.number({message: "Costo richiesto"}),
        details: z.string().or(z.literal("")).optional(),
    })).default([]),
});
   
export type CreateEventFormType = z.infer<typeof createEventSchema>;

The react-hook-form form and component:

const { control, handleSubmit, getValues, setError, clearErrors, formState: { errors }, reset: resetForm } = useForm<CreateEventFormType>({
    resolver: zodResolver(createEventSchema),
  });


<CustomRatesInput control={control} name="rates" />

The CustomRatesInput (it's not finished):

interface CustomRatesInputProps<T extends FieldValues> extends TextInputProps {
  control: Control<T>,
  name: ArrayPath<T>
}

const CustomRatesInput = <T extends FieldValues>({ control, name }: CustomRatesInputProps<T>) => {
  const { fields, append, remove } = useFieldArray({
    control,
    name,
  });

return (
    <View style={{ width: "100%" }}>
      <StyledText style={{ marginBottom: Spaces.small }}>Tariffe (opzionali):</StyledText>
      {fields.map((field, index) => (
        <View
          key={field.id}
          style={{
            flexDirection: "row"
          }}
        >
          <CustomInput name={`${name}.${index}.label` as Path<T>} control={control} />
        </View>
      ))}
      <CustomButton text="Aggiungi tariffa" onPress={() => append({ label: "", cost: 0, details: "" })} />
    </View>
  );
};

export default CustomRatesInput;

The problem is in the append() function, it seems to work but says:

"Object literal may only specify known properties, and 'label' does not exist in type 'FieldArray<T, ArrayPath>[]'"

and this happens with any field put as first in the object ("id", "cost", "label", whatever), same with another component for the "tags" array, I tried:

type Rate = {
  label: string;
  cost: number;
  details: string;
}

and

useFieldArray<Rate>()

but this cause another error with control and name inside useFieldArray:

"Type 'Control' is not assignable to type 'Control'. The types of '_subjects.state' are incompatible between these types. Type 'FormStateSubjectRef' is not assignable to type 'FormStateSubjectRef'. Type 'FormStateSubjectRef' is not assignable to type '{ readonly observers: Observer<Partial<FormState> & { name?: string | undefined; }>[]; subscribe: (value: Observer<Partial<FormState> & { ...; }>) => Subscription; unsubscribe: Noop; }'. Types of property 'observers' are incompatible. ..."

"Type 'ArrayPath' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'."

本文标签: Reacthookform useFieldArray typescript errorStack Overflow