You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.8 KiB
102 lines
2.8 KiB
import {
|
|
getNotes as getNotesBackend,
|
|
upsertNote as upsertNoteBackend
|
|
} from "./api";
|
|
|
|
const initialState = {
|
|
notes: [],
|
|
selectedNote: null,
|
|
error: null
|
|
};
|
|
|
|
export const reducer = (cs = initialState, { type, payload }) => {
|
|
switch (type) {
|
|
case "SELECT_NOTE":
|
|
return { ...cs, selectedNote: { ...payload.selectedNote } };
|
|
case "SAVE_NOTE_START":
|
|
return {
|
|
...cs,
|
|
selectedNote: { ...cs.selectedNote, content: payload.content }
|
|
};
|
|
case "SAVE_NOTE_SUCCESS":
|
|
return {
|
|
...cs,
|
|
selectedNote: { ...payload.note }
|
|
};
|
|
case "GET_NOTES_START":
|
|
return { ...cs, notesLoading: true };
|
|
case "GET_NOTES_SUCCESS":
|
|
return {
|
|
...cs,
|
|
notesLoading: false,
|
|
error: null,
|
|
notes: [...payload.notes]
|
|
};
|
|
case "SAVE_NOTE_FAIL":
|
|
case "GET_NOTES_FAIL":
|
|
return { ...cs, notesLoading: false, error: payload.error };
|
|
default:
|
|
return { ...cs };
|
|
}
|
|
};
|
|
|
|
const selectNote = ({ title }) => (dispatch, getState) => {
|
|
const normalizedTitle = title.toLocaleLowerCase();
|
|
const { selectedNote, notes } = getState().notes;
|
|
|
|
let foundNote = selectedNote;
|
|
const notesFilter = notes.filter(
|
|
n => n.title.toLocaleLowerCase() === normalizedTitle
|
|
);
|
|
if (notesFilter.length > 0) {
|
|
foundNote = notesFilter[0];
|
|
}
|
|
dispatch({ type: "SELECT_NOTE", payload: { selectedNote: foundNote } });
|
|
};
|
|
|
|
const deleteNote = ({ title }) => (dispatch, getState) => {};
|
|
|
|
const upsertNote = ({ title, content, tags = [] }) => async (
|
|
dispatch,
|
|
getState
|
|
) => {
|
|
dispatch({ type: "SAVE_NOTE_START", payload: { title, content, tags } });
|
|
try {
|
|
const result = await upsertNoteBackend({ title, content, tags });
|
|
dispatch(getNotes());
|
|
dispatch({ type: "SAVE_NOTE_SUCCESS", payload: { ...result } });
|
|
} catch (error) {
|
|
dispatch({ type: "SAVE_NOTE_FAIL", payload: { error } });
|
|
}
|
|
};
|
|
|
|
const getNotes = () => async (dispatch, getState) => {
|
|
const { notesLoading } = getState().notes;
|
|
if (notesLoading) {
|
|
console.warn(
|
|
"trying to load notes when the operation has already begun."
|
|
);
|
|
return;
|
|
}
|
|
|
|
dispatch({ type: "GET_NOTES_START" });
|
|
try {
|
|
const result = await getNotesBackend();
|
|
dispatch({ type: "GET_NOTES_SUCCESS", payload: result });
|
|
} catch (error) {
|
|
dispatch({ type: "GET_NOTES_FAIL", payload: { error } });
|
|
}
|
|
};
|
|
|
|
const updateTags = ({ title, tags }) => (dispatch, getState) => {
|
|
console.log(`adding tags ${tags} to ${title}`);
|
|
};
|
|
|
|
export const actions = {
|
|
getNotes,
|
|
deleteNote,
|
|
upsertNote,
|
|
selectNote,
|
|
updateTags
|
|
};
|