Ajout, modification et suppression de défi

This commit is contained in:
Emmy D'Anello 2024-12-14 12:36:50 +01:00
parent dba5b511ae
commit fd4b0e8cd1
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
3 changed files with 182 additions and 6 deletions

View File

@ -24,14 +24,16 @@ export default function MapScreen() {
visible={game.gameStarted || game.money > 0} visible={game.gameStarted || game.money > 0}
icon={(props) => <FontAwesome6 {...props} name='coins' size={20} />} icon={(props) => <FontAwesome6 {...props} name='coins' size={20} />}
color='black' color='black'
label={`${game.money}`} /> label={`${game.money}`}
onPress={() => {}} />
<FAB <FAB
style={styles.statusBadge} style={styles.statusBadge}
visible={game.gameStarted || game.money > 0} visible={game.gameStarted || game.money > 0}
size='small' size='small'
color='black' color='black'
icon={game.currentRunner ? 'run-fast' : () => <FontAwesome6 name='cat' size={20} />} icon={game.currentRunner ? 'run-fast' : () => <FontAwesome6 name='cat' size={20} />}
label={game.currentRunner ? "Coureuse" : "Poursuiveuse"} /> label={game.currentRunner ? "Coureuse" : "Poursuiveuse"}
onPress={() => {}} />
</View> </View>
<FreeChaseBanner /> <FreeChaseBanner />
</Surface> </Surface>

View File

@ -1,7 +1,10 @@
import ChallengeCard from "@/components/ChallengeCard" import ChallengeCard from "@/components/ChallengeCard"
import { useAddChallengeMutation, useDeleteChallengeMutation, useEditChallengeMutation } from "@/hooks/mutations/useChallengeMutation"
import { useAuth } from "@/hooks/useAuth"
import { useChallenges } from "@/hooks/useChallenges" import { useChallenges } from "@/hooks/useChallenges"
import { Challenge } from "@/utils/features/challenges/challengesSlice" import { Challenge } from "@/utils/features/challenges/challengesSlice"
import { FontAwesome6 } from "@expo/vector-icons" import { FontAwesome6 } from "@expo/vector-icons"
import { useQueryClient } from "@tanstack/react-query"
import { useRouter } from "expo-router" import { useRouter } from "expo-router"
import { useState } from "react" import { useState } from "react"
import { FlatList, StyleSheet } from "react-native" import { FlatList, StyleSheet } from "react-native"
@ -9,6 +12,8 @@ import { Appbar, Button, Dialog, Divider, FAB, List, MD3Colors, Modal, Portal, S
export default function ChallengesList() { export default function ChallengesList() {
const router = useRouter() const router = useRouter()
const queryClient = useQueryClient()
const auth = useAuth()
const challenges = useChallenges() const challenges = useChallenges()
const [editChallengeVisible, setEditChallengeVisible] = useState(false) const [editChallengeVisible, setEditChallengeVisible] = useState(false)
@ -23,6 +28,77 @@ export default function ChallengesList() {
const [errorVisible, setErrorVisible] = useState(false) const [errorVisible, setErrorVisible] = useState(false)
const [error, setError] = useState([200, ""]) const [error, setError] = useState([200, ""])
const addChallengeMutation = useAddChallengeMutation({
auth,
onPostSuccess: () => {
setSuccessMessage("Le défi a bien été ajouté !")
setSuccessSnackbarVisible(true)
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
},
onError: ({ response, error }) => {
setErrorVisible(true)
if (response)
setError([response.statusCode, response.message])
else if (error)
setError([400, error.message])
},
})
const editChallengeMutation = useEditChallengeMutation({
auth,
onPostSuccess: () => {
setSuccessMessage("Le défi a bien été modifié !")
setSuccessSnackbarVisible(true)
setEditChallengeVisible(false)
setDisplayedChallenge(null)
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
},
onError: ({ response, error }) => {
setErrorVisible(true)
if (response)
setError([response.statusCode, response.message])
else if (error)
setError([400, error.message])
},
})
const deleteChallengeMutation = useDeleteChallengeMutation({
auth,
onPostSuccess: () => {
setSuccessMessage("Le défi a bien été supprimé !")
setSuccessSnackbarVisible(true)
setEditChallengeVisible(false)
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'get-challenges' })
},
onError: ({ response, error }) => {
setErrorVisible(true)
if (response)
setError([response.statusCode, response.message])
else if (error)
setError([400, error.message])
},
})
function sendEditChallenge() {
if (editChallengeId) {
editChallengeMutation.mutate({
id: editChallengeId,
title: editChallengeTitle,
description: editChallengeDescription,
reward: editChallengeReward,
})
}
else {
addChallengeMutation.mutate({
title: editChallengeTitle,
description: editChallengeDescription,
reward: editChallengeReward,
})
}
}
function sendDeleteChallenge() {
displayedChallenge && deleteChallengeMutation.mutate(displayedChallenge)
}
return ( return (
<Surface style={{ flex: 1 }}> <Surface style={{ flex: 1 }}>
<Appbar.Header> <Appbar.Header>
@ -103,14 +179,14 @@ export default function ChallengesList() {
inputMode='numeric' inputMode='numeric'
onChangeText={(text) => setEditChallengeReward(+text)} onChangeText={(text) => setEditChallengeReward(+text)}
error={!editChallengeReward} error={!editChallengeReward}
onEndEditing={() => { }} /> onEndEditing={sendEditChallenge} />
</Dialog.Content> </Dialog.Content>
<Dialog.Actions> <Dialog.Actions>
<Button onPress={() => setEditChallengeVisible(false)}>Annuler</Button> <Button onPress={() => setEditChallengeVisible(false)}>Annuler</Button>
<Button <Button
onPress={() => { }} onPress={sendEditChallenge}
disabled={!editChallengeTitle || !editChallengeDescription || !editChallengeReward}> disabled={!editChallengeTitle || !editChallengeDescription || !editChallengeReward}>
Ajouter {editChallengeId ? "Modifier" : "Ajouter"}
</Button> </Button>
</Dialog.Actions> </Dialog.Actions>
</Dialog> </Dialog>
@ -123,7 +199,7 @@ export default function ChallengesList() {
</Dialog.Content> </Dialog.Content>
<Dialog.Actions> <Dialog.Actions>
<Button onPress={() => setConfirmDeleteVisible(false)}>Annuler</Button> <Button onPress={() => setConfirmDeleteVisible(false)}>Annuler</Button>
<Button onPress={() => { }}>Confirmer</Button> <Button onPress={sendDeleteChallenge}>Confirmer</Button>
</Dialog.Actions> </Dialog.Actions>
</Dialog> </Dialog>
</Portal> </Portal>

View File

@ -1,4 +1,5 @@
import { AuthState } from "@/utils/features/auth/authSlice" import { AuthState } from "@/utils/features/auth/authSlice"
import { Challenge } from "@/utils/features/challenges/challengesSlice"
import { useMutation } from "@tanstack/react-query" import { useMutation } from "@tanstack/react-query"
type ErrorResponse = { type ErrorResponse = {
@ -17,6 +18,12 @@ type ChallengeActionProps = {
onError?: onErrorFunc onError?: onErrorFunc
} }
type ChallengeProps = {
auth: AuthState
onPostSuccess?: onPostSuccessFunc
onError?: onErrorFunc
}
export const useDrawRandomChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeActionProps) => { export const useDrawRandomChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeActionProps) => {
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
@ -73,3 +80,94 @@ export const useEndChallenge = ({ auth, onPostSuccess, onError }: ChallengeActio
} }
}) })
} }
export const useAddChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeProps) => {
return useMutation({
mutationFn: async (challenge: Omit<Challenge, 'id'>) => {
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/`, {
method: "POST",
headers: {
"Authorization": `Bearer ${auth.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: challenge.title,
description: challenge.description,
reward: challenge.reward,
})
}).then(resp => resp.json())
},
onSuccess: async (data) => {
if (data.statusCode) {
if (onError)
onError({ response: data })
return
}
if (onPostSuccess)
onPostSuccess()
},
onError: async (error: Error) => {
if (onError)
onError({ error: error })
}
})
}
export const useEditChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeProps) => {
return useMutation({
mutationFn: async (challenge: Challenge) => {
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/${challenge.id}/`, {
method: "PATCH",
headers: {
"Authorization": `Bearer ${auth.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: challenge.title,
description: challenge.description,
reward: challenge.reward,
})
}).then(resp => resp.json())
},
onSuccess: async (data) => {
if (data.statusCode) {
if (onError)
onError({ response: data })
return
}
if (onPostSuccess)
onPostSuccess()
},
onError: async (error: Error) => {
if (onError)
onError({ error: error })
}
})
}
export const useDeleteChallengeMutation = ({ auth, onPostSuccess, onError }: ChallengeProps) => {
return useMutation({
mutationFn: async (challenge: Challenge) => {
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/challenges/${challenge.id}/`, {
method: "DELETE",
headers: {
"Authorization": `Bearer ${auth.token}`,
"Content-Type": "application/json",
},
}).then(resp => resp.json())
},
onSuccess: async (data) => {
if (data.statusCode) {
if (onError)
onError({ response: data })
return
}
if (onPostSuccess)
onPostSuccess()
},
onError: async (error: Error) => {
if (onError)
onError({ error: error })
}
})
}