-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.jsx
100 lines (89 loc) · 2.6 KB
/
App.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import React from "react";
import Sidebar from "./components/Sidebar";
import Editor from "./components/Editor";
import Split from "react-split";
import { onSnapshot, addDoc, doc, deleteDoc, setDoc } from "firebase/firestore";
import { notesCollection, db } from "./firebase";
export default function App() {
const [notes, setNotes] = React.useState([]);
const [currentNoteId, setCurrentNoteId] = React.useState("");
const [tempNoteText, setTempNoteText] = React.useState("");
const currentNote =
notes.find((note) => note.id === currentNoteId) || notes[0];
const sortedNotes = notes.sort((a, b) => {
return b.updatedAt - a.updatedAt;
});
React.useEffect(() => {
const unsubscribe = onSnapshot(notesCollection, function (snapshot) {
const notesArr = snapshot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
}));
setNotes(notesArr);
});
return unsubscribe;
}, []);
React.useEffect(() => {
if (currentNote) {
setTempNoteText(currentNote.body);
}
}, [currentNote]);
React.useEffect(() => {
const timeoutId = setTimeout(() => {
updateNote(tempNoteText);
}, 500);
return () => clearTimeout(timeoutId);
}, [tempNoteText]);
React.useEffect(() => {
if (!currentNoteId) {
setCurrentNoteId(notes[0]?.id);
}
}, [notes]);
async function createNewNote() {
const newNote = {
body: "# Type your markdown note's title here",
createdAt: Date.now(),
updatedAt: Date.now(),
};
const newNoteRef = await addDoc(notesCollection, newNote);
setCurrentNoteId(newNoteRef.id);
}
async function updateNote(text) {
const docRef = doc(db, "notes", currentNoteId);
await setDoc(
docRef,
{ body: text, updatedAt: Date.now() },
{ merge: true }
);
}
async function deleteNote(noteId) {
const docRef = doc(db, "notes", noteId);
await deleteDoc(docRef);
}
return (
<main>
{notes.length > 0 ? (
<Split sizes={[30, 70]} direction="horizontal" className="split">
<Sidebar
notes={sortedNotes}
currentNote={currentNote}
setCurrentNoteId={setCurrentNoteId}
newNote={createNewNote}
deleteNote={deleteNote}
/>
<Editor
tempNoteText={tempNoteText}
setTempNoteText={setTempNoteText}
/>
</Split>
) : (
<div className="no-notes">
<h1>You have no notes</h1>
<button className="first-note" onClick={createNewNote}>
Create one now
</button>
</div>
)}
</main>
);
}