diff options
Diffstat (limited to 'apps/Notes/helpers/noteActions.js')
-rw-r--r-- | apps/Notes/helpers/noteActions.js | 104 |
1 files changed, 104 insertions, 0 deletions
diff --git a/apps/Notes/helpers/noteActions.js b/apps/Notes/helpers/noteActions.js new file mode 100644 index 0000000..c296c97 --- /dev/null +++ b/apps/Notes/helpers/noteActions.js @@ -0,0 +1,104 @@ +import fetchJson from 'lib/fetchJson' + +export const getNote = async (note, setFetchedNote, setPopup, callback) => { + try { + const {content} = await fetchJson(`/api/note/${note.noteId}`) + setFetchedNote({ ...note, content}) + callback() + } catch (err) { + setFetchedNote() + setPopup({ + content: 'Could not open note', + time: 2000, + error: true, + }) + } +} + +export const addNote = async (e, mutateNotes, setAction, setPopup) => { + const content = e.currentTarget.content.value + const title = e.currentTarget.title.value + + try { + mutateNotes( + await fetchJson('/api/notes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({title, content}), + }) + ) + setPopup({ + content: 'New note added', + time: 2000, + }) + setAction('') + } catch (e) { + setPopup({ + content: 'Could not save note', + time: 2000, + error: true, + }) + } +} + +export const updateNote = async (e, note, mutateNotes, setAction, setPopup) => { + const content = e.currentTarget.content.value + const title = e.currentTarget.title.value + const {_id, noteId} = note + + try { + mutateNotes( + await fetchJson('/api/notes', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({_id, title, noteId, content}), + }) + ) + setPopup({ + content: 'Note updated', + time: 2000, + }) + setAction('') + } catch (e) { + setPopup({ + content: 'Could not update note', + time: 2000, + error: true, + }) + } +} + +export const removeNote = (e, _id, mutateNotes, setPopup, setAction) => { + e.stopPropagation() + + const remove = async () => { + try { + await mutateNotes( + await fetchJson('/api/notes', { + method: 'DELETE', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({_id}), + }) + ) + setPopup({ + content: 'Note was removed', + time: 2000, + }) + setAction('') + } catch (err) { + setPopup({ + content: 'Could not remove note', + time: 2000, + error: true, + }) + } + } + + setPopup({ + content: 'Do you want to remove note?', + yes: { label: 'Remove', action: remove }, + no: { label: 'Cancel', action: () => {} }, + error: true, + }) +} + |