Skip to content

Commit

Permalink
fix(dataloader): Fix dataloader implementation (#21)
Browse files Browse the repository at this point in the history
* Add failing case

* Add fix for failing case
  • Loading branch information
richardscarrott authored Oct 21, 2022
1 parent 872bfd4 commit c6cd8a8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
12 changes: 7 additions & 5 deletions dataloader/app/loaders/userLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import DataLoader from "dataloader";
import { db } from "~/data.server";

export const createUsersByIdLoader = () =>
new DataLoader(async (keys: Readonly<string[]>) =>
db.user.findMany({
new DataLoader(async (ids: Readonly<string[]>) => {
const users = await db.user.findMany({
where: {
id: {
in: keys,
in: ids,
},
},
})
);
});
const userMap = new Map(users.map((user) => [user.id, user]));
return ids.map((id) => userMap.get(id) ?? null);
});
9 changes: 6 additions & 3 deletions dataloader/app/routes/users/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ export const loader: LoaderFunction = async ({ context }) => {
"2cbad877-2da6-422d-baa6-c6a96a9e085f"
);
const user3 = context.loaders.usersById.load(
"does_not_exist"
);
const user4 = context.loaders.usersById.load(
"1dd9e502-343d-4acb-9391-2bc52d5ea904"
);
const users = await Promise.all([user1, user2, user3]);
const users = await Promise.all([user1, user2, user3, user4]);

return json({ users });
};
Expand All @@ -38,8 +41,8 @@ export default function UserEmails() {
<section>
<h2>Emails</h2>
<ul>
{users.map((user) => (
<li key={user.email}>{user.email}</li>
{users.map((user, i) => (
<li key={i}>{user ? user.email : 'Not found'}</li>
))}
</ul>
</section>
Expand Down

0 comments on commit c6cd8a8

Please sign in to comment.