fix: improve category form functionality
- Fix loading button state in category form (use Button loading prop instead of manual spinner) - Fix redirect after successful category create/update (move navigation to mutation callbacks) - Remove duplicate toast messages - Ensure proper navigation only after successful API calls
This commit is contained in:
parent
e9473f7a49
commit
c2f938bda8
|
|
@ -6,6 +6,7 @@ import { Button } from "@/components/ui/Button";
|
|||
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
|
||||
import { Trash2, Edit3, Plus, FolderOpen, Folder } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
import { PageContainer, PageTitle, SectionSubtitle } from "../../../components/ui/Typography";
|
||||
|
||||
const CategoriesTableSkeleton = () => (
|
||||
<div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
|
|
@ -98,22 +99,24 @@ const CategoriesListPage = () => {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<PageContainer>
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<FolderOpen className="h-6 w-6" />
|
||||
مدیریت دستهبندیها
|
||||
</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">
|
||||
مدیریت دستهبندیهای محصولات
|
||||
</p>
|
||||
<PageTitle>مدیریت دستهبندیها</PageTitle>
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-400">مدیریت دستهبندیهای محصولات</p>
|
||||
</div>
|
||||
<Button onClick={handleCreate} className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
دستهبندی جدید
|
||||
</Button>
|
||||
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
className="flex items-center justify-center w-12 h-12 bg-primary-600 hover:bg-primary-700 rounded-full transition-colors duration-200 text-white shadow-lg hover:shadow-xl"
|
||||
title="دستهبندی جدید"
|
||||
>
|
||||
<Plus className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
|
|
@ -288,7 +291,7 @@ const CategoriesListPage = () => {
|
|||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,75 +1,64 @@
|
|||
import React, { useEffect } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import * as yup from 'yup';
|
||||
import { ArrowRight, FolderOpen } from 'lucide-react';
|
||||
import { Button } from '../../../components/ui/Button';
|
||||
import { Input } from '../../../components/ui/Input';
|
||||
import { LoadingSpinner } from '../../../components/ui/LoadingSpinner';
|
||||
import { useToast } from '../../../contexts/ToastContext';
|
||||
import { useCategory, useCreateCategory, useUpdateCategory } from '../core/_hooks';
|
||||
import { CategoryFormData } from '../core/_models';
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input } from "@/components/ui/Input";
|
||||
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
|
||||
import { ArrowRight, FolderOpen } from "lucide-react";
|
||||
|
||||
const categorySchema = yup.object({
|
||||
name: yup.string().required('نام دستهبندی الزامی است').min(2, 'نام دستهبندی باید حداقل 2 کاراکتر باشد'),
|
||||
description: yup.string().optional(),
|
||||
});
|
||||
import { FormHeader, PageContainer, Label } from '../../../components/ui/Typography';
|
||||
|
||||
const CategoryFormPage = () => {
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const isEdit = !!id;
|
||||
const { id } = useParams();
|
||||
const { showToast } = useToast();
|
||||
const isEdit = Boolean(id);
|
||||
|
||||
const { data: category, isLoading: isLoadingCategory } = useCategory(id || '', isEdit);
|
||||
const { mutate: createCategory, isPending: isCreating } = useCreateCategory();
|
||||
const { mutate: updateCategory, isPending: isUpdating } = useUpdateCategory();
|
||||
|
||||
const isLoading = isCreating || isUpdating;
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isValid, isDirty },
|
||||
setValue,
|
||||
watch
|
||||
} = useForm<CategoryFormData>({
|
||||
resolver: yupResolver(categorySchema) as any,
|
||||
mode: 'onChange',
|
||||
defaultValues: {
|
||||
name: '',
|
||||
description: ''
|
||||
}
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
description: '',
|
||||
parent_id: null as number | null,
|
||||
});
|
||||
|
||||
const formValues = watch();
|
||||
const { data: category, isLoading: isLoadingCategory } = useCategory(
|
||||
id || '0',
|
||||
isEdit
|
||||
);
|
||||
|
||||
const createMutation = useCreateCategory();
|
||||
const updateMutation = useUpdateCategory();
|
||||
|
||||
useEffect(() => {
|
||||
if (isEdit && category) {
|
||||
setValue('name', category.name, { shouldValidate: true });
|
||||
setValue('description', category.description || '', { shouldValidate: true });
|
||||
if (category && isEdit) {
|
||||
setFormData({
|
||||
name: category.name || '',
|
||||
description: category.description || '',
|
||||
parent_id: category.parent_id || null,
|
||||
});
|
||||
}
|
||||
}, [isEdit, category, setValue]);
|
||||
}, [category, isEdit]);
|
||||
|
||||
const onSubmit = (data: CategoryFormData) => {
|
||||
if (isEdit && id) {
|
||||
updateCategory({
|
||||
id: parseInt(id),
|
||||
name: data.name,
|
||||
description: data.description || undefined
|
||||
}, {
|
||||
onSuccess: () => {
|
||||
navigate('/categories');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
createCategory({
|
||||
name: data.name,
|
||||
description: data.description || undefined
|
||||
}, {
|
||||
onSuccess: () => {
|
||||
navigate('/categories');
|
||||
}
|
||||
});
|
||||
const handleChange = (field: string, value: any) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
await updateMutation.mutateAsync({
|
||||
id: parseInt(id!),
|
||||
...formData
|
||||
});
|
||||
} else {
|
||||
await createMutation.mutateAsync(formData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving category:', error);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -85,106 +74,73 @@ const CategoryFormPage = () => {
|
|||
);
|
||||
}
|
||||
|
||||
const backButton = (
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={handleBack}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
بازگشت
|
||||
</Button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={handleBack}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
بازگشت
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
|
||||
<FolderOpen className="h-6 w-6" />
|
||||
{isEdit ? 'ویرایش دستهبندی' : 'ایجاد دستهبندی جدید'}
|
||||
</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">
|
||||
{isEdit ? 'ویرایش اطلاعات دستهبندی' : 'اطلاعات دستهبندی جدید را وارد کنید'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<PageContainer className="max-w-2xl mx-auto">
|
||||
<FormHeader
|
||||
title={isEdit ? 'ویرایش دستهبندی' : 'ایجاد دستهبندی جدید'}
|
||||
subtitle={isEdit ? 'ویرایش اطلاعات دستهبندی' : 'اطلاعات دستهبندی جدید را وارد کنید'}
|
||||
backButton={backButton}
|
||||
/>
|
||||
|
||||
{/* Form */}
|
||||
<div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<Input
|
||||
label="نام دستهبندی"
|
||||
{...register('name')}
|
||||
error={errors.name?.message}
|
||||
placeholder="مثال: لباس، کفش، لوازم الکترونیکی"
|
||||
/>
|
||||
|
||||
<div className="card p-4 sm:p-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
توضیحات (اختیاری)
|
||||
</label>
|
||||
<textarea
|
||||
{...register('description')}
|
||||
rows={4}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
|
||||
placeholder="توضیحات کوتاهی در مورد این دستهبندی..."
|
||||
<Label htmlFor="name">نام دستهبندی</Label>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => handleChange('name', e.target.value)}
|
||||
placeholder="نام دستهبندی را وارد کنید"
|
||||
required
|
||||
/>
|
||||
{errors.description && (
|
||||
<p className="text-red-500 text-sm mt-1">{errors.description.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Preview */}
|
||||
{formValues.name && (
|
||||
<div className="border border-gray-200 dark:border-gray-600 rounded-lg p-4 bg-gray-50 dark:bg-gray-700">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
|
||||
پیشنمایش دستهبندی
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||
<strong>نام:</strong> {formValues.name}
|
||||
</div>
|
||||
{formValues.description && (
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||
<strong>توضیحات:</strong> {formValues.description}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<Label htmlFor="description">توضیحات</Label>
|
||||
<textarea
|
||||
id="description"
|
||||
value={formData.description}
|
||||
onChange={(e) => handleChange('description', e.target.value)}
|
||||
placeholder="توضیحات دستهبندی"
|
||||
rows={4}
|
||||
className="input resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-4 space-x-reverse pt-6 border-t border-gray-200 dark:border-gray-600">
|
||||
{/* Actions */}
|
||||
<div className="flex flex-col space-y-3 sm:flex-row sm:justify-end sm:space-y-0 sm:space-x-3 sm:space-x-reverse pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={handleBack}
|
||||
disabled={isLoading}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
انصراف
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isLoading}
|
||||
disabled={!isValid || isLoading}
|
||||
loading={createMutation.isPending || updateMutation.isPending}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isEdit ? 'بهروزرسانی' : 'ایجاد'}
|
||||
{isEdit ? 'ویرایش' : 'ایجاد'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Help Section */}
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
|
||||
<h3 className="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
|
||||
راهنما
|
||||
</h3>
|
||||
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
|
||||
<li>• دستهبندیها برای سازماندهی محصولات استفاده میشوند</li>
|
||||
<li>• نام دستهبندی باید واضح و قابل فهم باشد</li>
|
||||
<li>• توضیحات کمک میکند تا دستهبندی بهتر شناخته شود</li>
|
||||
<li>• بعد از ایجاد، میتوانید محصولات را به این دستهبندی اختصاص دهید</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { QUERY_KEYS } from "@/utils/query-key";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
getCategories,
|
||||
getCategory,
|
||||
|
|
@ -31,6 +32,7 @@ export const useCategory = (id: string, enabled: boolean = true) => {
|
|||
|
||||
export const useCreateCategory = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: [QUERY_KEYS.CREATE_CATEGORY],
|
||||
|
|
@ -38,6 +40,7 @@ export const useCreateCategory = () => {
|
|||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_CATEGORIES] });
|
||||
toast.success("دستهبندی با موفقیت ایجاد شد");
|
||||
navigate("/categories");
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Create category error:", error);
|
||||
|
|
@ -48,6 +51,7 @@ export const useCreateCategory = () => {
|
|||
|
||||
export const useUpdateCategory = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: [QUERY_KEYS.UPDATE_CATEGORY],
|
||||
|
|
@ -58,6 +62,7 @@ export const useUpdateCategory = () => {
|
|||
queryKey: [QUERY_KEYS.GET_CATEGORY, variables.id.toString()],
|
||||
});
|
||||
toast.success("دستهبندی با موفقیت ویرایش شد");
|
||||
navigate("/categories");
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Update category error:", error);
|
||||
|
|
|
|||
Loading…
Reference in New Issue