2

I have the following schema in my RHF form:

const latexSchema = z.string().refine(
  () => {
    return solutionRef.current?.editor?.state.doc.textContent.length! >= 10;
  },
  'Wymagane jest co najmniej 10 znaków.'
);
const imagesSchema = files.min(1, 'Wymagany jest co najmniej jeden plik.');
const videoSchema = file;

const currentUserQuery = useCurrentUser();
const user = currentUserQuery.data!;

const schema = useMemo(
  () => saveHomeworkSchema.extend({
    description: saveHomeworkSchema.shape.description.refine(
      () => descriptionRef.current?.editor?.state.doc.textContent.length! >= 10,
      'Wymagane jest co najmniej 10 znaków.'
    ),
    solution: solution
      .refine(
        (solution) => {
          return (
            latexSchema.safeParse(solution?.latex).success ||
            imagesSchema.safeParse(solution?.images).success ||
            videoSchema.safeParse(solution?.video).success ||
            solutionSteps.min(1).safeParse(solution?.steps).success
          );
        },
        {
          path: [''],
          message: 'Musisz podać przynajmniej jeden format rozwiązania.',
        }
      )
      .refine(
        (solution) =>
          !solution?.video?.uploading ||
          solution?.images?.some((el) => el.uploading),
        {
          path: [''],
          message: 'Trwa przesyłanie pliku...',
        }
      ),
    }),
  []
);

So I want to add an error to solution field when none of solution.latex, solution.images etc. are valid. The problem is that even though the refine is running, the errors.solution is not updated... I have mode:all on my form and resolver: zodResolver(schema). As a workaround I added:

useEffect(() => {
  const callback = subscribe({
    formState: {
      values: true,
    },
    callback: ({ name }) => {
      if (name?.startsWith('solution')) {
        trigger('solution');
        trigger(name as FieldPath<HomeworkSchemaType>);
      }
    },
  });

  return () => callback();
}, [subscribe]);

But I don't think its a good solution. Any ideas why refine does not updated errors in that case? I guess this is beacuse my initial solution schema is

export const solutionSteps = z.array(solutionStep);

export const solution = z.object({
  latex: z.string().nullable(),
  images: z.array(file),
  video: file.nullable(),
  files: z.array(z.string()),
  steps: solutionSteps,
});

so it's valid by default but I expected that refine will help here.

1
  • If you add a console.log, is the condition in the refine failing/succeeding when you expect it? Commented Nov 14 at 16:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.