refactor: enhance form validation and error handling in EditField, DefaultSelect, and Form components
This commit is contained in:
@@ -4,35 +4,51 @@ import { Button } from "@mui/material";
|
||||
import ArrowLeftB from "@/components/icons/ArrowLeftB";
|
||||
import { request } from "@/services/response";
|
||||
|
||||
function SubmitData({ setStep, data, prevData }) {
|
||||
function SubmitData({ setStep, data, prevData, setErrors }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const newStep = () => setStep((prev) => prev + 1);
|
||||
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = async () => {
|
||||
const isChanged = JSON.stringify(prevData) !== JSON.stringify(data);
|
||||
|
||||
// پاک کردن error های قبلی
|
||||
setErrors({});
|
||||
|
||||
if (isChanged) {
|
||||
setLoading(true);
|
||||
let newData = data;
|
||||
const { basic_insurance, name, national_code, uuid } = newData;
|
||||
const { basic_insurance, supplementary_insurance, name, family, national_code, gender, insurance_id, uuid } = data;
|
||||
|
||||
newData = {
|
||||
basic_insurance: [basic_insurance.value?.id],
|
||||
...(prevData.name?.value === data.name.value ? {} : { name: name }),
|
||||
...(prevData.national_code?.value
|
||||
? {}
|
||||
: { national_code: national_code }),
|
||||
const payload = {
|
||||
name: name?.value,
|
||||
family: family?.value,
|
||||
national_code: national_code?.value,
|
||||
gender: gender?.value,
|
||||
insurance_id: insurance_id?.value,
|
||||
basic_insurance: basic_insurance?.value?.id ? [basic_insurance.value.id] : [],
|
||||
supplementary_insurance: supplementary_insurance?.value?.id ? [supplementary_insurance.value.id] : [],
|
||||
};
|
||||
|
||||
request
|
||||
.patchUserProfile(newData, uuid)
|
||||
.then(() => {
|
||||
setLoading(false);
|
||||
newStep();
|
||||
})
|
||||
.catch(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
try {
|
||||
if (uuid) {
|
||||
// اگر uuid داریم، پروفایل وجود داره و باید PATCH کنیم
|
||||
console.log('📤 ارسال درخواست PATCH - UUID:', uuid, 'Payload:', payload);
|
||||
await request.patchUserProfile(payload, uuid);
|
||||
} else {
|
||||
// اگر uuid نداریم، پروفایل وجود نداره و باید POST کنیم
|
||||
console.log('📤 ارسال درخواست POST - Payload:', payload);
|
||||
await request.postUserProfile(payload);
|
||||
}
|
||||
console.log('✅ پروفایل با موفقیت ذخیره شد');
|
||||
setLoading(false);
|
||||
newStep();
|
||||
} catch (error) {
|
||||
console.log('❌ خطا در ذخیره پروفایل:', error?.response?.data || error);
|
||||
setLoading(false);
|
||||
// اگر خطای validation بود، error ها را ست میکنیم
|
||||
if (error?.response?.data) {
|
||||
setErrors(error.response.data);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newStep();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user