2024-05-15 11:44:10 +00:00
|
|
|
import { useEffect, useLayoutEffect, useRef } from "react";
|
|
|
|
import { createUserAccount, devlog } from "@frontend/kitui";
|
|
|
|
import { isAxiosError } from "axios";
|
|
|
|
|
|
|
|
import { makeRequest } from "@api/makeRequest";
|
|
|
|
|
|
|
|
import type { UserAccount } from "@frontend/kitui";
|
2024-11-21 13:25:26 +00:00
|
|
|
import { setUserAccount } from "@/stores/user";
|
2024-05-15 11:44:10 +00:00
|
|
|
|
|
|
|
export const useUserAccountFetcher = <T = UserAccount>({
|
|
|
|
onError,
|
|
|
|
onNewUserAccount,
|
|
|
|
url,
|
|
|
|
userId,
|
|
|
|
}: {
|
|
|
|
url: string;
|
|
|
|
userId: string | null;
|
|
|
|
onNewUserAccount: (response: T) => void;
|
|
|
|
onError?: (error: any) => void;
|
|
|
|
}) => {
|
|
|
|
const onNewUserAccountRef = useRef(onNewUserAccount);
|
|
|
|
const onErrorRef = useRef(onError);
|
|
|
|
useLayoutEffect(() => {
|
|
|
|
onNewUserAccountRef.current = onNewUserAccount;
|
|
|
|
onErrorRef.current = onError;
|
|
|
|
}, [onError, onNewUserAccount]);
|
|
|
|
useEffect(() => {
|
|
|
|
if (!userId) return;
|
|
|
|
const controller = new AbortController();
|
|
|
|
makeRequest<never, T>({
|
|
|
|
url,
|
|
|
|
contentType: true,
|
|
|
|
method: "GET",
|
|
|
|
useToken: true,
|
|
|
|
withCredentials: false,
|
|
|
|
signal: controller.signal,
|
|
|
|
})
|
|
|
|
.then((result) => {
|
|
|
|
devlog("User account", result);
|
2024-11-24 13:53:15 +00:00
|
|
|
console.log(result)
|
2024-11-21 13:25:26 +00:00
|
|
|
if (result) onNewUserAccountRef.current(result);
|
2024-05-15 11:44:10 +00:00
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
devlog("Error fetching user account", error);
|
2024-08-05 12:39:11 +00:00
|
|
|
if (error.response?.status === 409) return;
|
2024-05-15 11:44:10 +00:00
|
|
|
if (isAxiosError(error) && error.response?.status === 404) {
|
|
|
|
createUserAccount(controller.signal, url.replace("get", "create"))
|
|
|
|
.then((result) => {
|
|
|
|
devlog("Created user account", result);
|
2024-11-21 13:25:26 +00:00
|
|
|
console.log("это пойдёт в стор: ")
|
|
|
|
console.log(result)
|
|
|
|
if (result) onNewUserAccountRef.current(result.created_account as T);
|
2024-05-15 11:44:10 +00:00
|
|
|
})
|
|
|
|
.catch((error) => {
|
2024-08-24 13:44:56 +00:00
|
|
|
if (error.response?.status === 409) return;
|
2024-05-15 11:44:10 +00:00
|
|
|
devlog("Error creating user account", error);
|
|
|
|
onErrorRef.current?.(error);
|
|
|
|
});
|
|
|
|
} else {
|
2024-11-24 13:53:15 +00:00
|
|
|
console.log(error)
|
2024-05-15 11:44:10 +00:00
|
|
|
onErrorRef.current?.(error);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return () => controller.abort();
|
|
|
|
}, [url, userId]);
|
|
|
|
};
|