Array not being added to Firebase

huangapple go评论45阅读模式
英文:

Array not being added to Firebase

问题

仍在学习 Firebase。我正在创建一个论坛,尝试将数据保存在 Firebase 中,以便在刷新页面时数据不会消失。我已添加了一些测试数据,并且它运行得非常顺利。然而,当我用通过 useState 不断更新的数组替换我的测试数据时,Firebase 中只保存了一个空数组,并且当我刷新页面时,我创建的所有主题都消失了。

在点击“创建主题”按钮后,用户输入主题标题和消息。一切都存储在 topic 数组中,每个主题都作为该数组中的对象保存。该对象包含一些值,如主题的标题、创建它的用户和日期。消息也保存了,但我目前只在前端页面上进行工作,显示所有主题的列表。然后,我有一些代码遍历数组并对主题进行排序/显示在主页上。

const [topic, setTopic] = useState([]);

const [title, setTitle] = useState();
const [message, setMessage] = useState();

const addTopic = (e) => {
    e.preventDefault();
    setTopic([
      ...topic, // 数组
      {
        id: 4,
        title: title,
        message,
        author: "Dagger",
        count: 1,
        date: new Date(),
      },
    ]);

    try {
      const docRef = addDoc(collection(firestore, "topics"), {
        topic, // 我试图添加的数组
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
};
英文:

Still learning Firebase. I'm creating a forum and I'm trying to save the data in Firebase so the data won't disappear when I refresh the page. I added some test data and I got it working just fine. However, when I replace my test data with an array I'm working with that is constantly updated via useState I just get an empty array saved inside Firebase and all the topics I made disappear again when I refresh the page.

Upon clicking a Create Topic button the user inputs a topic title and a message. Everything is stored inside the topic array and each topic is saved as an object inside that array. The object holds a few values like the title of the topic, the user who created it and the date. The message is also saved however I'm just working on the front page for now which displays a list of all the topics. I then have some code which maps through the array and sorts / displays the topics on the main page.

const [topic, setTopic] = useState([]);

const [title, setTitle] = useState();
const [message, setMessage] = useState();

const addTopic = (e) => {
    e.preventDefault();
    setTopic([
      ...topic, // the array
      {
        id: 4,
        title: title,
        message,
        author: "Dagger",
        count: 1,
        date: new Date(),
      },
    ]);

    try {
      const docRef = addDoc(collection(firestore, "topics"), {
        topic, // the array I'm trying to add
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
  };

答案1

得分: 1

代码部分已经排除,以下是翻译的内容:

问题在于您正在使用尚未更新的 topic 变量。您应该注意,useState 不会立即更新变量。

您可以使用以下方式进行更改。

const [topic, setTopic] = useState([]);

const [title, setTitle] = useState();
const [message, setMessage] = useState();

const addTopic = (e) => {
    e.preventDefault();

    const updatedTopic = [
      ...topic,
      {
        id: 4,
        title: title,
        message,
        author: "Dagger",
        count: 1,
        date: new Date(),
      }
    ];

    setTopic(updatedTopic);

    try {
      const docRef = addDoc(collection(firestore, "topics"), {
        updatedTopic,
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
};
英文:

The problem is that you are using the topic variable which hasn't been updated yet. You should note that useState doesn't update the variable immediately.

You can do this instead.

const [topic, setTopic] = useState([]);

const [title, setTitle] = useState();
const [message, setMessage] = useState();

const addTopic = (e) => {
    e.preventDefault();

    const updatedTopic = [
      ...topic,
      {
        id: 4,
        title: title,
        message,
        author: "Dagger",
        count: 1,
        date: new Date(),
      }
    ];

    setTopic(updatedTopic);

    try {
      const docRef = addDoc(collection(firestore, "topics"), {
        updatedTopic,
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
  };

huangapple
  • 本文由 发表于 2023年2月19日 17:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定