arashi-devA
tRPC3y ago
2 replies
arashi-dev

dynamic query and mutation

Hello. I have an edit form component like this:

    const router = useRouter()
    const { t } = useTranslation(["admin/common"])
    const productId = useMemo(() => router.isReady ? (Array.isArray(router.query.id) ? router.query.id[0] : router.query.id) : undefined, [router.isReady, router.query.id])

    const { data, status } = trpc.admin.products.findOne.useQuery({
        id: +productId!,
    }, {
        enabled: !!productId
    })

    const utils = trpc.useContext()
    const mutate = trpc.admin.products.update.useMutation({
        onSuccess() {
            showNotification({
                message: t("admin/common:messages.success.edit"),
                color: "green"
            })
            utils.admin.products.getAll.invalidate()
        },
        onError() {
            showNotification({
                message: t("admin/common:messages.error.unexpected"),
                color: "red"
            })
        }
    })

    const form = useForm({
        initialValues: data!,
        validateInputOnChange: true,
        validate: zodResolver(productSchema.update),
    })

    ...


this code is going to be repeated for different models (Product, User, Color, Category, etc.). so, I am looking for a way to make it DRY and reusable.
the only difference between them is the model name in trpc trpc.admin.THE_MODEL_NAME and the validation schema. the rest are just same and repeated

how can I make it reusable? I thought maybe I can create a Component for it and pass fetchData, updateData props to handle the query and mutations. but they are harder to manage as I can't track the status and abort on unmount
Was this page helpful?