66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
import { useQuery } from "@tanstack/react-query";
|
|
import { getUser } from "~/lib/api/client/user";
|
|
import type { UserId } from "~/lib/api/types";
|
|
import { useUsersStore } from "~/stores/users-store";
|
|
|
|
async function fetchCurrentUser() {
|
|
const { setCurrentUserId, addUser } = useUsersStore.getState();
|
|
|
|
const user = await import("~/lib/api/client/user").then((m) => m.default.me());
|
|
setCurrentUserId(user.id);
|
|
addUser(user);
|
|
|
|
return null;
|
|
}
|
|
|
|
export const useFetchCurrentUser = () => {
|
|
const query = useQuery({
|
|
queryKey: ["users", "@me"],
|
|
queryFn: fetchCurrentUser,
|
|
});
|
|
|
|
return query;
|
|
};
|
|
|
|
export const useFetchUser = (userId: UserId) => {
|
|
const query = useQuery({
|
|
queryKey: ["users", userId],
|
|
queryFn: async () => {
|
|
if (useUsersStore.getState().users[userId]) {
|
|
return null;
|
|
}
|
|
|
|
const response = await getUser(userId);
|
|
|
|
useUsersStore.getState().addUser(response);
|
|
|
|
return null;
|
|
},
|
|
});
|
|
|
|
return query;
|
|
};
|
|
|
|
export const useFetchUsers = (userIds: UserId[]) => {
|
|
const query = useQuery({
|
|
queryKey: ["users", ...userIds],
|
|
queryFn: async () => {
|
|
const userIdsToFetch = userIds.filter((userId) => !useUsersStore.getState().users[userId]);
|
|
|
|
if (userIdsToFetch.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
const response = await Promise.all(userIds.map(getUser));
|
|
|
|
for (const user of response) {
|
|
useUsersStore.getState().addUser(user);
|
|
}
|
|
|
|
return null;
|
|
},
|
|
});
|
|
|
|
return query;
|
|
};
|