scrimba
Learn React
Notes & Tenzies
Challenge: createdAt and updatedAt
Go Pro!Bootcamp

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

Challenge: createdAt and updatedAt
AboutCommentsNotes
Challenge: createdAt and updatedAt
Expand for more info
App.jsx
run
preview
console
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("")

const currentNote =
notes.find(note => note.id === currentNoteId)
|| notes[0]

/**
* Challenge:
* 1. Add createdAt and updatedAt properties to the notes
* When a note is first created, set the `createdAt` and `updatedAt`
* properties to `Date.now()`. Whenever a note is modified, set the
* `updatedAt` property to `Date.now()`.
*
* 2. TBA
*/

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"
}
const newNoteRef = await addDoc(notesCollection, newNote)
setCurrentNoteId(newNoteRef.id)
}

async function updateNote(text) {
const docRef = doc(db, "notes", currentNoteId)
await setDoc(docRef, { body: text }, { 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={notes}
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>
)
}
Console
/index.html
-2:54