Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

javascript - Ask about how to get react data from firebase

import React, { useEffect, useState } from "react";
import { dbService } from "./myFirebase";

function Editor({ userObj }) {
  const [myContent, setMyContent] = useState("");
  const [myContents, setMyContents] = useState([]);
  const getValue = (event) => {
    const { name, value } = event.target;
    setMyContent({ ...myContent, [name]: value });
  };

  useEffect(() => {
    console.log("1", myContents);
    dbService.collection("contents").onSnapshot((snapshot) => {
      const communityArray = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      setMyContents(communityArray);
      console.log("2", myContents);
    });
    console.log("3", myContents);
  }, []);
  console.log("4", myContents);

  const addContent = async (event) => {
    event.preventDefault();
    await dbService.collection("contents").add({
      content: myContent,
      createdAt: Date.now(),
    });
    setMyContent("");
  };
  return (
    <div>
      <button type="submit" onClick={addContent}>
        {" "}
        input{" "}
      </button>
    </div>
  );
}
export default Editor;

enter image description here

When data is entered in this way, I coded it to be saved and received in Firebase.

If I print the log, it comes out as an empty array and then the value is entered. So when I get it, if I say console.log("10", myContents[0].id);, it is properly received, but when I refresh it, TypeError: Cannot read property'id' of undefined appears.

I think it's because of that empty array, how do I fix it? Are you using async await for useEffect? I tried, but it was the same, was it wrong?

question from:https://stackoverflow.com/questions/65932094/ask-about-how-to-get-react-data-from-firebase

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...