I'm new to Firebase Firestore (and real-time databases altogether) and I've been experimenting with the real-time features that it provides via the onSnapShot
function and I'm wondering what is considered "expensive" in terms of the frequency and number of writes I make to the database.
I'm currently working on a task management app for teams (sort of like Asana), and I want the creation and updating of tasks to update in real-time on all clients in the group, and it's the editing of items where I start to wonder about the expense.
Here is a simplified version of my current setup:
App.js:
const App = () => {
const [todoList, setTodoList] = useState([]);
useEffect(() => {
const todoQuery = query(collection(db, "todos"));
const unsubscribe = onSnapshot(todoQuery, (querySnapshot) => {
const todos = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setTodoList(todos);
});
return () => unsubscribe();
}, []);
return (
<div className="App">
{todoList.map((item) => (
<TodoItem key={item.id} item={item} />
))}
</div>
);
}
export default App;
TodoItem.js:
const TodoItem = ({ item }) => {
const editItem = async ({ target: { value } }) => {
const updatedItem = {
...item,
text: value,
};
// is this expensive?
const docToUpdate = doc(db, "todos", item.id);
await setDoc(docToUpdate, updatedItem);
};
const toggleCompletion = async () => {
const updatedItem = {
...item,
isComplete: !item.isComplete,
};
const docToUpdate = doc(db, "todos", item.id);
await setDoc(docToUpdate, updatedItem);
};
return (
<div>
<input
type="checkbox"
checked={item.isComplete}
onChange={toggleCompletion}
/>
{item.todoId}:
<input value={item.text} onChange={editItem} />
</div>
);
}
The area of concern is in the editItem
function change handler that is called each time a keystroke is made in the <input />
. This function writes to the database on every keystroke, which results in real-time updates on other clients due to the onSnapshot
listener, however, I feel that this is not a good idea. But, as mentioned before, I am new to Firestore and am not sure what exactly classifies expensive operations.
Any advice would be greatly appreciated!