.
This commit is contained in:
46
app/hooks/use-fetch-user.ts
Normal file
46
app/hooks/use-fetch-user.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
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";
|
||||
|
||||
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;
|
||||
};
|
||||
Reference in New Issue
Block a user