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;
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…