Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created August 15, 2022 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanflorence/1e7f5d3344c0db4a8394292c157cd305 to your computer and use it in GitHub Desktop.
Save ryanflorence/1e7f5d3344c0db4a8394292c157cd305 to your computer and use it in GitHub Desktop.
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);
});
}
@mtliendo
Copy link

mtliendo commented Apr 17, 2024

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 a first, last, avatar, and notes 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment