我正在尝试做一个简单的firebase to-do app。我可以写todos,没有问题。但是,当我尝试删除一个todos或者将一个todos标记为完成时,id
似乎是undefined
,firebase找不到有问题的todos。我该如何纠正这个问题呢?关于上下文,我正在学习这个教程:https://www.youtube.com/watch?v=cuvP4h6O2x8&t=755s
编码:
import "../App.css";
import {useState} from "react";
import {auth, firestore} from "../firebase";
import firebase from "../firebase";
import {useCollectionData} from "react-firebase-hooks/firestore";
const Todos = () => {
const [todo, setTodo] = useState("");
const todosRef = firestore.collection(`users/${auth.currentUser.uid}/todos`);
const [todos] = useCollectionData(todosRef, { idField: "id" });
const signOut = () => auth.signOut();
const onSubmitTodo = (event) => {
event.preventDefault();
setTodo("");
todosRef.add({
text: todo,
complete: false,
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
});
};
return (
<>
<header>
<button onClick = {signOut}>Sign Out</button>
</header>
<main>
<form onSubmit = {onSubmitTodo}>
<input
required
value = {todo}
onChange = {(e) => setTodo(e.target.value)}
placeholder="what's next?"
/>
<button type="submit"> Add </button>
</form>
{todos && todos.map((todo)=> <Todo key={todo.id} {...todo} />)}
</main>
</>
);
};
const Todo = ({ id, complete, text}) => {
const todosRef = firestore.collection(`users/${auth.currentUser.uid}/todos`);
const onCompleteTodo = (id, complete) =>
todosRef.doc(id).set({ complete: !complete }, { merge: true });
const onDeleteTodo = (id) => todosRef.doc(id).delete();
return (
<div key={id} className="todo">
<button
className={`todo-item ${complete ? "complete" : ""}`}
tabIndex="0"
onClick={()=> onCompleteTodo(id, complete)}
>
{text}
</button>
<button onClick={() => onDeleteTodo(id)}>x</button>
</div>
);
};
export default Todos;
2条答案
按热度按时间sg2wtvxw1#
FirestoreDataConverter
接口。请参阅文档。
这些示例使用TypeScript,但在您的情况下,应该可以使用类似下面的方法,在获取集合后立即应用
withConverter
和自定义转换器:uhry853o2#
转到rules并使用以下代码键入edit: