import * as Storage from '../services/Storage' const save = async ({ userId, stateRef, router, id, setNotes, }) => { stateRef.current.updatedAt = new Date().toISOString() const newNote = await Storage.save({ userId, })('notes')(stateRef.current) if (router.query.id !== id) { await router.replace( { pathname: '/notes/[id]', query: { id, }, }, undefined, { shallow: true, } ) } setNotes(oldNotes => { let notes if (oldNotes.some((a) => a.id === id)) { notes = oldNotes.map(n => n.id === id ? newNote : n) } else { notes = [newNote, ...oldNotes] } return notes.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) }) } const triggerAutoSave = ({ stateRef, timeoutRef, router, id, setNotes, userId, }) => { if (timeoutRef.current !== null) { clearTimeout(timeoutRef.current) } timeoutRef.current = setTimeout(async () => { await save({ userId, stateRef, router, id, setNotes, }) timeoutRef.current = null }, 3000) } export const updateContent = ({ stateRef, timeoutRef, router, id, setNotes, userId, }) => e => { stateRef.current.content = e triggerAutoSave({ userId, stateRef, timeoutRef, router, id, setNotes, }) } export const updateTitle = ({ stateRef, timeoutRef, router, id, setNotes, setTitle, userId, }) => e => { setTitle(stateRef.current.title = e.target.value) triggerAutoSave({ userId, stateRef, timeoutRef, router, id, setNotes, }) } export const remove = ({ setNotes, notes, router, userId, }) => note => async () => { setNotes(notes.filter(n => n.id !== note.id)) await router.replace( { pathname: '/notes', }, undefined, { shallow: true, } ) const result = await Storage.remove({ userId, })('notes')(note) if (!result) { setNotes(notes) } } export const load = async ({ setNotes, userId, }) => { const theNotes = await Storage.load({ userId, })('notes') setNotes(theNotes) }