11<script setup lang="ts">
22import { watch } from ' vue' ;
3- import { useRoute } from ' vue-router' ;
4- import { useMutation , useQueryClient } from ' @tanstack/vue-query' ;
5- import clientsApi from ' @/api/clientsApi' ;
3+ import { useRoute , useRouter } from ' vue-router' ;
64import LoadingModalComponent from ' @/shared/components/LoadingModalComponent.vue' ;
75import useClient from ' @/clients/composables/useClient' ;
8- import type { Client } from ' @/clients/interfaces/client' ;
96
107const route = useRoute ();
11- const queryClient = useQueryClient ();
8+ const router = useRouter ();
129
13- const { client, isLoading } = useClient ( + route .params .id );
14-
15- const updateClient = async ( client : Client ): Promise <Client > => {
16- // await new Promise( resolve => {
17- // setTimeout( () => resolve( true ), 1500 )
18- // });
19- const { data } = await clientsApi .patch <Client >(` /${client .id } ` , client );
20- const queries = queryClient .getQueryCache ().findAll ([' clients?page=' ], { exact: false });
21- queries .forEach ( query => query .fetch () );
22- return data ;
23- }
24-
25- const clientMutation = useMutation ( updateClient );
10+ const {
11+ clientMutation,
12+ client,
13+ isError,
14+ isLoading,
15+ isUpdating,
16+ isUpdatingSuccess,
17+ updateClient
18+ } = useClient ( + route .params .id );
2619
2720watch (clientMutation .isSuccess , () => {
2821 setTimeout (() => {
2922 clientMutation .reset ();
3023 }, 2000 );
3124});
3225
26+ watch (isError , () => {
27+ if ( isError .value ) router .replace (' /clients' );
28+ });
29+
3330 </script >
3431
3532<template >
36- <h3 v-if =" clientMutation.isLoading.value " >Saving...</h3 >
37- <h3 v-if =" clientMutation.isSuccess.value " >Saved</h3 >
33+ <h3 v-if =" isUpdating " >Saving...</h3 >
34+ <h3 v-if =" isUpdatingSuccess " >Saved</h3 >
3835<LoadingModalComponent v-if =" isLoading" />
3936<div v-if =" client" >
4037 <h2 >{{ client.name }}</h2 >
41- <form @submit.prevent =" clientMutation.mutate (client!)" >
38+ <form @submit.prevent =" updateClient (client!)" >
4239 <input
4340 type =" text"
4441 placeholder =" Name"
@@ -53,7 +50,7 @@ watch(clientMutation.isSuccess, () => {
5350 <br >
5451 <button
5552 type =" submit"
56- :disabled =" clientMutation.isLoading.value "
53+ :disabled =" isUpdating "
5754 >
5855 Save
5956 </button >
0 commit comments