Files
ticcat/resources/js/hooks/AxiosTools.tsx
Romulus21 a34eadb51f auth work
2024-07-17 07:09:04 +02:00

43 lines
1.3 KiB
TypeScript

import React, {useState} from "react"
import axios, {AxiosError} from "axios"
import {cleanErrorsForm, displayFormErrors} from "../utilities/form"
const useAxiosTools = (isLoading = false) => {
const [loading, setLoading] = useState(isLoading)
const [error, setError] = useState<string|null>(null)
const axiosGet = axios.get
const axiosPost = axios.post
const axiosPut = axios.put
const axiosDelete = axios.delete
const errorCatch = (error: Error|AxiosError|unknown) => {
if (axios.isAxiosError(error)) {
if (error.response?.status === 422) {
displayFormErrors(error)
} else if (error.response?.status === 401) {
console.log('not authorise')
} else {
setError(error.response?.data.message || error.message)
}
} else if (error instanceof Error) {
setError(error.message)
}
}
const errorLabel = () => {
return error ? <div className="m-2 mx-auto rounded bg-red-600 px-2 py-1 text-center text-white">{error}</div>: null
}
const cleanErrors = () => {
cleanErrorsForm()
setError(null)
}
return {loading, setLoading, error, setError, errorCatch, errorLabel, cleanErrors, axiosGet, axiosPost, axiosPut, axiosDelete}
}
export default useAxiosTools