NextJs Firebase v9 Part 9: Update the todo
In the previous article, we already see the major difference between a new todo and a selected todo is, the selected todo has timestamp.
So to determine whether user want to update or want to add a new todo, we can check whether the todo has timestamp.
Video tutorials and Source code
But before all of these, we have to import the following from firestore package. The doc
, updateDoc
and serverTimestamp
.
import { collection, serverTimestamp, addDoc, doc, updateDoc } from "firebase/firestore";
At the onSubmit function, it todo has property “timestamp”, we will update with the new value and also updated the updated time. After that, we clear the field by setting both title and detail as empty string.
At last we show a blue alert to let user know the todo is updated successfully.
const onSubmit = async () => {if (todo?.hasOwnProperty('timestamp')) {const docRef = doc(db, "todos", todo.id);const todoUpdated = { ...todo, timestamp: serverTimestamp() }updateDoc(docRef, todoUpdated)setTodo({ title: ''…