Explorer
project
components
Editor.jsx
Sidebar.jsx
App.jsx
firebase.js
index.html
index.jsx
style.css
Dependencies
firebase@9.20.0
nanoid@3.1.28
react-dom@17.0.2
react-mde@11.5.0
react-split@2.0.13
react@17.0.2
showdown@1.9.1
Bootcamp
Study group
Collaborate with peers in your dedicated #study-group channel.
Code reviews
Submit projects for review using the /review
command in your #code-reviews channel
import React from "react"
import Sidebar from "./components/Sidebar"
import Editor from "./components/Editor"
import Split from "react-split"
import { nanoid } from "nanoid"
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("")
/**
* Challenge:
* 1. Set up a new state variable called `tempNoteText`. Initialize
* it as an empty string
* 2. Change the Editor so that it uses `tempNoteText` and
* `setTempNoteText` for displaying and changing the text instead
* of dealing directly with the `currentNote` data.
* 3. Create a useEffect that, if there's a `currentNote`, sets
* the `tempNoteText` to `currentNote.body`. (This copies the
* current note's text into the `tempNoteText` field so whenever
* the user changes the currentNote, the editor can display the
* correct text.
* 4. TBA
*/
const currentNote =
notes.find(note => note.id === currentNoteId)
|| notes[0]
const sortedNotes = notes.sort((a, b) => 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 (!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
currentNote={currentNote}
updateNote={updateNote}
/>
</Split>
:
<div className="no-notes">
<h1>You have no notes</h1>
<button
className="first-note"
onClick={createNewNote}
>
Create one now
</button>
</div>
}
</main>
)
}