Firebase未在useCollectionData中返回ID

c9x0cxw0  于 2022-11-25  发布在  其他
关注(0)|答案(2)|浏览(88)

我正在尝试做一个简单的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;
sg2wtvxw

sg2wtvxw1#

    • React Firebase Hooks v5Firebase 9**及更高版本匹配,在该版本中应使用FirestoreDataConverter接口。

请参阅文档。
这些示例使用TypeScript,但在您的情况下,应该可以使用类似下面的方法,在获取集合后立即应用withConverter和自定义转换器:

const converter = {
    toFirestore(post) {
        return {
            text: post.text,
        }
    },
    fromFirestore(snapshot, options) {
        const data = snapshot.data(options)
        return {
            id: snapshot.id,
            text: data.text,
        }
    },
}

const todosRef = firestore
    .collection(`users/${auth.currentUser.uid}/todos`)
    .withConverter(converter);
uhry853o

uhry853o2#

转到rules并使用以下代码键入edit:

allow read, write: if request.time>timestamp.date(2022, 11, 23);

相关问题