11import { type BetInsert , type Deck , type Game } from '@/types' ;
22import { supabase } from '@/providers/supabase' ;
3+ import { UseMutationOptions , useQueryClient } from '@tanstack/react-query' ;
34import { api } from './api' ;
45
5- export const gameKey = ( gameId : string ) => {
6- return [ 'game' , gameId ] ;
6+ export const gameKey = ( ) => {
7+ return [ 'game' ] ;
78} ;
89
910export const trumpKey = ( gameId : string , roundNumber : number ) => {
@@ -12,7 +13,7 @@ export const trumpKey = (gameId: string, roundNumber: number) => {
1213
1314export const updateGame = ( gameId : string , token : string ) => {
1415 return {
15- queryKey : gameKey ( gameId ) ,
16+ queryKey : gameKey ( ) ,
1617 queryFn : async ( ) : Promise < Game > => {
1718 if ( ! gameId ) return { } as Game ;
1819
@@ -77,7 +78,11 @@ export const finishRoundMutation = (token: string) => {
7778 } ;
7879} ;
7980
80- export const playMutation = ( token : string ) => {
81+ export const usePlayMutation = (
82+ token : string ,
83+ ) : UseMutationOptions < void , Error , string , unknown > => {
84+ const queryClient = useQueryClient ( ) ;
85+
8186 return {
8287 mutationFn : async ( id : string ) : Promise < void > => {
8388 try {
@@ -96,6 +101,45 @@ export const playMutation = (token: string) => {
96101 // ignore error
97102 }
98103 } ,
104+ onMutate : async ( id : string ) => {
105+ await queryClient . cancelQueries ( { queryKey : gameKey ( ) } ) ;
106+
107+ const previousGame = queryClient . getQueryData < Game > ( gameKey ( ) ) ;
108+
109+ if ( previousGame ) {
110+ const turn =
111+ previousGame . player_cards
112+ . sort ( ( a , b ) => a . turn - b . turn )
113+ . findLast ( ( c ) => c . turn ) ?. turn || 1 ;
114+
115+ const currentCard = previousGame . player_cards . find ( ( c ) => c . id === id ) ;
116+
117+ const updatedGame = {
118+ ...previousGame ,
119+ player_cards : previousGame . player_cards . map ( ( card ) => {
120+ if ( card . id === id ) return { ...card , status : 'on table' , turn } ;
121+
122+ if (
123+ card . user_id === currentCard ?. user_id &&
124+ card . status === 'on table'
125+ )
126+ return { ...card , status : 'played' , turn } ;
127+
128+ return card ;
129+ } ) ,
130+ } ;
131+
132+ queryClient . setQueryData ( gameKey ( ) , updatedGame ) ;
133+ }
134+
135+ return previousGame ;
136+ } ,
137+ onError : ( err , newTodo , context ) => {
138+ queryClient . setQueryData ( gameKey ( ) , context ) ;
139+ } ,
140+ onSettled : ( ) => {
141+ queryClient . invalidateQueries ( { queryKey : gameKey ( ) } ) ;
142+ } ,
99143 } ;
100144} ;
101145
0 commit comments