Initializing Input Fields Using useFieldArray

98 views Asked by At

I've encountered a problem while working with an array of empty strings to store image data and attempting to use the useFieldArray hook to manage these fields. Initially, the array appears to have a length of 0, which means there are no input fields for images upon the page's first load. However, when I press the "Add Image" button, it creates input fields as expected why I'm not getting the initial input for images.

Could you help me understand what might be causing this issue?

            const {
            register,
            reset,
            handleSubmit,
            formState: { errors },
          } = useForm<newProduct>({
            defaultValues: {
              title: '',
              price: 0,
              description: '',
              images: [''],
              categoryId: 0,
            },
        resolver: yupResolver(newProductSchema),
      });


  const { fields, append, remove } = useFieldArray({ name: 'images' });

 

       {fields.map((field, index) => (
          <Box
            key={field.id}
            sx={{
              display: 'flex',
            }}
          >
            <TextField
              fullWidth
              type="text"
              id={`images[${index}]`}
              label="images"
              {...register(`images.${index}`)}
              helperText={errors.images?.message}
              error={errors.images ? true : false}
            />
            {index > 0 && (
              <MuiButton onClick={() => remove(index)}>
                <DeleteForeverIcon style={{ color: 'black' }} />
              </MuiButton>
            )}
          </Box>
        ))}
0

There are 0 answers