Replies: 1 comment
-
how about
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
how about
|
Beta Was this translation helpful? Give feedback.
-
I need some help understanding why the firstName field loses focus when the isDirty state changes. When I remove the formState from my useForm call, the firstName field doesn't lose focus. I've tried removing the useEffect and blocker code, but that doesn't resolve the issue either. For some reason my form is unmounting and mounting when isDirty changes state. Here's the code:
import { useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { unstable_useBlocker as useBlocker } from "react-router-dom";
import {
Grid,
Button,
FormGroup,
Checkbox,
Typography,
Box,
FormControlLabel,
TextField,
} from "@mui/material";
import MemberPrayers from "./MemberPrayers";
import MemberTalks from "./MemberTalks";
import MemberCallings from "./MemberCallings";
import ProfileLabel from "./ProfileLabel";
import ProfileItem from "./ProfileItem";
import ConfirmationDialog from "../../components/ConfirmationDialog";
import { calculateAge, formatDate } from "../../utils/helpers";
// Define a validation schema using zod
const memberProfileSchema = z.object({
firstName: z.string().optional(),
isWillingToAcceptCalling: z.boolean().optional(),
isWillingToPray: z.boolean().optional(),
isWillingToSpeak: z.boolean().optional(),
contactForTithing: z.boolean().optional(),
isServingMission: z.boolean().optional(),
});
const ProfileForm = ({ member, updateMember, meetings, callings }) => {
const age = calculateAge(member.birthDate);
const birthday = formatDate(member.birthDate, "LLL d");
// Create a form using react-hook-form, using zod for validation
const {
control,
handleSubmit,
formState: { isDirty },
reset,
} = useForm({
defaultValues: {
...member,
},
resolver: zodResolver(memberProfileSchema),
});
// Block the user from leaving the page if there are unsaved changes
let blocker = useBlocker(
({ currentLocation, nextLocation }) =>
isDirty && currentLocation.pathname !== nextLocation.pathname
);
// Reset the form when the member changes
useEffect(() => {
reset(member);
}, [member]);
const gender = member.gender === "M" ? "Male" : "Female";
// Save the member data, reset the form, and unblock the user
const handleSaveMember = (data) => {
updateMember.mutate({ id: member._id, ...data });
reset(data);
};
return (
<Box sx={{ width: "100%" }} mt={2}>
{blocker.state === "blocked" && (
<ConfirmationDialog
open={blocker.state === "blocked"}
title="Unsaved Changes!"
message="Are you sure you want to leave without saving?"
onConfirm={() => blocker.proceed()}
onCancel={() => blocker.reset()}
/>
)}
);
};
export default ProfileForm;
Beta Was this translation helpful? Give feedback.
All reactions