Utilisation de mutations plutôt que d'appels fetch directs
This commit is contained in:
49
client/hooks/mutations/useLoginMutation.ts
Normal file
49
client/hooks/mutations/useLoginMutation.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import { AuthPayload } from "@/utils/features/location/authSlice"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
|
||||
type ErrorResponse = {
|
||||
error: string
|
||||
message: string
|
||||
statusCode: number
|
||||
}
|
||||
|
||||
type LoginForm = {
|
||||
name: string
|
||||
password: string
|
||||
}
|
||||
|
||||
type onPostSuccessFunc = () => void
|
||||
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
||||
type onErrorFunc = (props: ErrorFuncProps) => void
|
||||
|
||||
type LoginProps = {
|
||||
authLogin: (payload: AuthPayload) => { payload: AuthPayload, type: "auth/login" }
|
||||
onPostSuccess?: onPostSuccessFunc
|
||||
onError?: onErrorFunc
|
||||
}
|
||||
|
||||
export const useLoginMutation = ({ authLogin, onPostSuccess, onError }: LoginProps) => {
|
||||
return useMutation({
|
||||
mutationFn: ({ name, password }: LoginForm) => {
|
||||
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/auth/login/`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: name, password: password })
|
||||
}).then(resp => resp.json())
|
||||
},
|
||||
onSuccess: (data, { name, password }: LoginForm) => {
|
||||
if (data.error) {
|
||||
if (onError)
|
||||
onError({ response: data })
|
||||
return
|
||||
}
|
||||
authLogin({ name: name, password: password, token: data.accessToken })
|
||||
if (onPostSuccess)
|
||||
onPostSuccess()
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
if (onError)
|
||||
onError({ error: error })
|
||||
}
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user