Spaces:
Build error
Build error
import { useState } from "react" | |
import axios from "@/utils/axios"; | |
import { Options } from "redaxios"; | |
export const useRequest = (method: "post" | "put" | "patch" | "delete" | "get", endpoint: string, params: Options, body: Options | undefined) => { | |
const [loading, setLoading] = useState<boolean>(false) | |
const [data, setData] = useState<any>(null) | |
const submit = async () => { | |
setLoading(true); | |
const url = new URL(endpoint, process.env.NEXT_PUBLIC_APP_APIURL); | |
if (params) { | |
const parameters = Object.entries(params).filter( | |
([_, value]) => | |
value !== "" && | |
value !== null && | |
value !== undefined && | |
value !== false | |
); | |
parameters.forEach(([key, value]) => { | |
url.searchParams.append(key, value as string); | |
}); | |
} | |
console.log( | |
"Requesting", | |
method, | |
url.pathname, | |
url.searchParams.toString(), | |
body | |
) | |
const needBody = ["post", "put", "patch"].includes(method); | |
axios[method](url.pathname, needBody ? body : { | |
params: url.searchParams | |
}) | |
.then((res: any) => { | |
if (res.ok) { | |
setData(res.data); | |
} | |
}) | |
.catch((err) => { | |
setData(err.data); | |
}) | |
.finally(() => setLoading(false)); | |
}; | |
return { | |
submit, | |
loading, | |
setLoading, | |
data | |
} | |
} |