Open History to see the last commit
1import localforage from "localforage";
2import { matchSorter } from "match-sorter";
3import sortBy from "sort-by";
4β
5const seed = async () => {
6 const initialData = [
7 {
8 avatar: "https://avatars.githubusercontent.com/u/5580297?v=4",
9 createdAt: 1660978713047,
10 favorite: false,
11 first: "Tanner",
12 id: "usupkc1",
13 last: "Linsley",
14 notes: "Created React Query",
15 twitter: "@tannerlinsley",
16 },
17 {
18 avatar: "https://avatars.githubusercontent.com/u/1021430",
19 createdAt: 1660979124264,
20 favorite: false,
21 first: "Dominik",
22 id: "kvvztl7",
23 last: "D",
24 notes: "Maintains React Query",
25 twitter: "@tkdodo",
26 },
27 ];
28 const contacts = await localforage.getItem("contacts");
29 if (!contacts) {
30 set(initialData);
31 }
32};
33β
34seed();
35β
36export async function getContacts(query) {
37 await fakeNetwork(`getContacts:${query}`);
38 let contacts = await localforage.getItem("contacts");
39 if (!contacts) contacts = [];
40 if (query) {
41 contacts = matchSorter(contacts, query, { keys: ["first", "last"] });
42 }
43 return contacts.sort(sortBy("last", "createdAt"));
44}
45β
46export async function createContact() {
47 await fakeNetwork();
48 let id = Math.random().toString(36).substring(2, 9);
49 let contact = { id, createdAt: Date.now() };
50 let contacts = await getContacts();
51 contacts.unshift(contact);
52 await set(contacts);
53 return contact;
54}
55β
56export async function getContact(id) {
57 await fakeNetwork(`contact:${id}`);
58 let contacts = await localforage.getItem("contacts");
59 let contact = contacts.find((contact) => contact.id === id);
60 return contact ?? null;
61}
62β
63export async function updateContact(id, updates) {
64 await fakeNetwork();
65 let contacts = await localforage.getItem("contacts");
66 let contact = contacts.find((contact) => contact.id === id);
67 if (!contact) throw new Error("No contact found for", id);
68 Object.assign(contact, updates);
69 await set(contacts);
70 return contact;
71}
72β
73export async function deleteContact(id) {
74 let contacts = await localforage.getItem("contacts");
75 let index = contacts.findIndex((contact) => contact.id === id);
76 if (index > -1) {
77 contacts.splice(index, 1);
78 await set(contacts);
79 return true;
80 }
81 return false;
82}
83β
84function set(contacts) {
85 return localforage.setItem("contacts", contacts);
86}
87β
88async function fakeNetwork() {
89 return new Promise((res) => {
90 setTimeout(res, Math.random() * 800);
91 });
92}