Skip to content

Commit

Permalink
fix: fixing queries
Browse files Browse the repository at this point in the history
  • Loading branch information
daithihearn committed Jan 27, 2024
1 parent 6e3e1ca commit 4c93db1
Show file tree
Hide file tree
Showing 10 changed files with 63 additions and 88 deletions.
6 changes: 3 additions & 3 deletions src/caches/GameSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Player } from "model/Player"
import { RoundStatus } from "model/Round"
import { RootState } from "./caches"

const initialState: GameState = {
export const initialGameState: GameState = {
revision: -1,
iamSpectator: true,
isMyGo: false,
Expand All @@ -19,7 +19,7 @@ const initialState: GameState = {

export const gameSlice = createSlice({
name: "game",
initialState: initialState,
initialState: initialGameState,
reducers: {
updateGame: (_, action: PayloadAction<GameState>) => action.payload,
updatePlayers: (state, action: PayloadAction<Player[]>) => {
Expand All @@ -32,7 +32,7 @@ export const gameSlice = createSlice({
disableActions: state => {
state.isMyGo = false
},
resetGame: () => initialState,
resetGame: () => initialGameState,
},
})

Expand Down
22 changes: 3 additions & 19 deletions src/components/Game/Actions/PlayCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,25 +93,9 @@ const PlayCard = () => {
)

const selectCardToPlay = useCallback(() => {
if (selectedCards.length === 1)
dispatch(updateCardToPlay(selectedCards[0]))
}, [selectedCards])

// 1. Play card when you've pre-selected a card
// 2. If best card lead or lead from bottom enabled, play worst card
// 3. If lead from the top enabled, play best card
useEffect(() => {
if (round?.suit && gameId && isMyGo) {
if (cardToPlay) playCard({ gameId, card: cardToPlay })
else if (autoPlay === "worst" || bestCardLead(round)) {
const worstCard = getWorstCard(myCards, round)
if (worstCard) playCard({ gameId, card: worstCard.name })
} else if (autoPlay === "best") {
const bestCard = getBestCard(myCards, round)
if (bestCard) playCard({ gameId, card: bestCard.name })
}
}
}, [playCard, gameId, autoPlay, round, isMyGo, myCards, cardToPlay])
if (selectedCards.length === 1 && gameId)
playCard({ gameId, card: selectedCards[0].name })
}, [gameId, selectedCards])

return (
<ButtonGroup disableElevation variant="contained" size="large">
Expand Down
20 changes: 8 additions & 12 deletions src/components/Hooks/useGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,26 @@ export const useGame = () => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return []
}
const res = await axios.get(
const res = await axios.get<Game[]>(
`${process.env.REACT_APP_API_URL}/api/v1/game/all`,
getDefaultConfig(accessToken),
)
return res.data
},
refetchInterval: 5 * 60_000,
enabled: !!accessToken,
})

const createGame = useMutation({
mutationFn: async (createGame: CreateGame) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
if (accessToken) {
axios.put<Game>(
`${process.env.REACT_APP_API_URL}/api/v1/game`,
createGame,
getDefaultConfig(accessToken),
)
}
axios.put<Game>(
`${process.env.REACT_APP_API_URL}/api/v1/game`,
createGame,
getDefaultConfig(accessToken),
)
},
onSuccess: data =>
queryClient.invalidateQueries({ queryKey: ["myGames"] }),
Expand Down
36 changes: 13 additions & 23 deletions src/components/Hooks/useGameActions.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useMutation, useQueryClient } from "@tanstack/react-query"
import useAccessToken from "auth/accessToken"
import axios from "axios"
import { updateGame } from "caches/GameSlice"
import { initialGameState, updateGame } from "caches/GameSlice"
import { updateMyCards } from "caches/MyCardsSlice"
import { useAppDispatch } from "caches/hooks"
import { Card, CardName } from "model/Cards"
import { GameState } from "model/Game"
import { Suit } from "model/Suit"
import { useSnackbar } from "notistack"
import { getDefaultConfig } from "utils/AxiosUtils"
Expand All @@ -25,11 +26,9 @@ export const useGameActions = () => {
call: string
}) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return initialGameState
}
const response = await axios.put(
const response = await axios.put<GameState>(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}/call?call=${call}`,
null,
getDefaultConfig(accessToken),
Expand All @@ -53,11 +52,9 @@ export const useGameActions = () => {
cards: CardName[]
}) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return initialGameState
}
const response = await axios.put(
const response = await axios.put<GameState>(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}/buy`,
{ cards },
getDefaultConfig(accessToken),
Expand All @@ -83,9 +80,7 @@ export const useGameActions = () => {
suit: Suit
}) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return initialGameState
}
const response = await axios.put(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}/suit`,
Expand Down Expand Up @@ -114,9 +109,7 @@ export const useGameActions = () => {
card: CardName
}) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return initialGameState
}
const response = await axios.put(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}/play?card=${card}`,
Expand All @@ -135,15 +128,12 @@ export const useGameActions = () => {

const deleteGame = useMutation({
mutationFn: async ({ gameId }: { gameId: string }) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
if (accessToken) {
axios.delete(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}`,
getDefaultConfig(accessToken),
)
}
axios.delete(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}`,
getDefaultConfig(accessToken),
)
},
onSuccess: () =>
queryClient.invalidateQueries({
Expand Down
7 changes: 4 additions & 3 deletions src/components/Hooks/useGameState.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useQuery } from "@tanstack/react-query"
import useAccessToken from "auth/accessToken"
import axios from "axios"
import { updateGame } from "caches/GameSlice"
import { initialGameState, updateGame } from "caches/GameSlice"
import { updateMyCards } from "caches/MyCardsSlice"
import { useAppDispatch } from "caches/hooks"
import { GameState } from "model/Game"
import { useState } from "react"
import { getDefaultConfig } from "utils/AxiosUtils"

Expand All @@ -20,9 +21,9 @@ export const useGameState = (gameId: string) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return initialGameState
}
const res = await axios.get(
const res = await axios.get<GameState>(
`${process.env.REACT_APP_API_URL}/api/v1/game/${gameId}/state?revision=${revision}`,
getDefaultConfig(accessToken),
)
Expand Down
33 changes: 18 additions & 15 deletions src/components/Hooks/useProfiles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,14 @@ export const useProfiles = () => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return {
id: "",
name: "",
picture: "",
lastAccess: "",
}
}
const res = await axios.get(
const res = await axios.get<PlayerProfile>(
`${process.env.REACT_APP_API_URL}/api/v1/profile`,
getDefaultConfig(accessToken),
)
Expand All @@ -42,7 +47,7 @@ export const useProfiles = () => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return []
}
const res = await axios.get(
`${process.env.REACT_APP_API_URL}/api/v1/profile/all`,
Expand All @@ -58,20 +63,18 @@ export const useProfiles = () => {
// Mutations
const updateProfile = useMutation({
mutationFn: async (profile: UpdateProfilePayload) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
if (accessToken) {
await axios.put<PlayerProfile>(
`${process.env.REACT_APP_API_URL}/api/v1/profile`,
profile,
getDefaultConfig(accessToken),
)
}
axios.put<PlayerProfile>(
`${process.env.REACT_APP_API_URL}/api/v1/profile`,
profile,
getDefaultConfig(accessToken),
)
},
onSuccess: data => {
queryClient.setQueryData(["myProfile", accessToken], data)
queryClient.setQueryData(["playerProfiles", accessToken], data)
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["myProfile", "playerProfiles"],
})
},
onError: e => enqueueSnackbar(e.message, { variant: "error" }),
})
Expand Down
17 changes: 9 additions & 8 deletions src/components/Hooks/useSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ export const useSettings = () => {
queryKey: ["playerSettings", accessToken],
queryFn: async () => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return {
autoBuyCards: false,
}
}
const res = await axios.get(
const res = await axios.get<PlayerSettings>(
`${process.env.REACT_APP_API_URL}/api/v1/settings`,
getDefaultConfig(accessToken),
)
Expand All @@ -34,15 +34,16 @@ export const useSettings = () => {
const updateSettings = useMutation({
mutationFn: async (settings: PlayerSettings) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return {
autoBuyCards: false,
}
}
axios.put<PlayerSettings>(
const res = await axios.put<PlayerSettings>(
`${process.env.REACT_APP_API_URL}/api/v1/settings`,
settings,
getDefaultConfig(accessToken),
)
return res.data
},
onSuccess: data =>
queryClient.setQueryData(["playerSettings", accessToken], data),
Expand Down
4 changes: 2 additions & 2 deletions src/components/Hooks/useStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export const useStats = (playerId: string) => {
if (!accessToken) {
// Handle the case when accessToken is undefined
// For example, return a default value or throw an error
throw new Error("Access token is not available")
return []
}
const response = await axios.get(
const response = await axios.get<PlayerGameStats[]>(
`${
process.env.REACT_APP_API_URL
}/api/v1/stats/${encodeURIComponent(playerId)}`,
Expand Down
4 changes: 2 additions & 2 deletions src/components/StartNewGame/StartNewGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const StartNewGame = () => {

const togglePlayer = useCallback(
(player: PlayerProfile) => {
if (selectedPlayers.includes(player)) {
if (selectedPlayers?.includes(player)) {
setSelectedPlayers(
selectedPlayers.filter(p => p.id !== player.id),
)
Expand Down Expand Up @@ -159,7 +159,7 @@ const StartNewGame = () => {
onClick={() =>
togglePlayer(player)
}
selected={selectedPlayers.includes(
selected={selectedPlayers?.includes(
player,
)}
sx={{
Expand Down
2 changes: 1 addition & 1 deletion src/utils/GameUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const processOrderedCardsAfterGameUpdate = (

// Find the delta between the existing cards and the updated cards we got from the api
const delta = currentCardsNoBlanks.filter(
x => !updatedCardNames.includes(x.name),
x => !updatedCardNames?.includes(x.name),
)

// 1. If cards in payload match ordered cards then don't change orderedCards
Expand Down

0 comments on commit 4c93db1

Please sign in to comment.