Created
August 15, 2022 17:14
-
-
Save ryanflorence/1e7f5d3344c0db4a8394292c157cd305 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import localforage from "localforage"; | |
import { matchSorter } from "match-sorter"; | |
import sortBy from "sort-by"; | |
export async function getContacts(query) { | |
await fakeNetwork(`getContacts:${query}`); | |
let contacts = await localforage.getItem("contacts"); | |
if (!contacts) contacts = []; | |
if (query) { | |
contacts = matchSorter(contacts, query, { keys: ["first", "last"] }); | |
} | |
return contacts.sort(sortBy("last", "createdAt")); | |
} | |
export async function createContact() { | |
await fakeNetwork(); | |
let id = Math.random().toString(36).substring(2, 9); | |
let contact = { id, createdAt: Date.now() }; | |
let contacts = await getContacts(); | |
contacts.unshift(contact); | |
await set(contacts); | |
return contact; | |
} | |
export async function getContact(id) { | |
await fakeNetwork(`contact:${id}`); | |
let contacts = await localforage.getItem("contacts"); | |
let contact = contacts.find(contact => contact.id === id); | |
return contact ?? null; | |
} | |
export async function updateContact(id, updates) { | |
await fakeNetwork(); | |
let contacts = await localforage.getItem("contacts"); | |
let contact = contacts.find(contact => contact.id === id); | |
if (!contact) throw new Error("No contact found for", id); | |
Object.assign(contact, updates); | |
await set(contacts); | |
return contact; | |
} | |
export async function deleteContact(id) { | |
let contacts = await localforage.getItem("contacts"); | |
let index = contacts.findIndex(contact => contact.id === id); | |
if (index > -1) { | |
contacts.splice(index, 1); | |
await set(contacts); | |
return true; | |
} | |
return false; | |
} | |
function set(contacts) { | |
return localforage.setItem("contacts", contacts); | |
} | |
// fake a cache so we don't slow down stuff we've already seen | |
let fakeCache = {}; | |
async function fakeNetwork(key) { | |
if (!key) { | |
fakeCache = {}; | |
} | |
if (fakeCache[key]) { | |
return; | |
} | |
fakeCache[key] = true; | |
return new Promise(res => { | |
setTimeout(res, Math.random() * 800); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Going through this section in the react-router getting started tut, it looks like this file's
createContact
method is missing the ability to create afirst
,last
,avatar
, andnotes
setting. Otherwise, when testing out the/contact/:contactId/edit
route, it breaks.Alternatively, I just made the
defaultValues
on the form optional:defaultValue={contact?.first}
. Happy to PR if you think that'd be better to have in the docs.