[英]How can I add an object to my firestore from the frontend with react? Keep getting the error Uncaught Error: Objects are not valid as a React child
I want to add an object to my firestore that looks like this: ]我想向我的 firestore 添加一个 object,如下所示:]
This is the code where I add the object:这是我添加 object 的代码:
updateDoc(usersRef, { //adding username to users field in firestore
users: arrayUnion({ username: "yeah", items: items })
})
If I need this object in this specific way how else can I do this?如果我以这种特定方式需要这个 object 我还能怎么做? Does anyone have any ideas?有人有什么想法吗?
I tried looking around and there are similar posts but they are mostly by mistake and not people needing actual objects.我试着环顾四周,发现有类似的帖子,但它们大多是错误的,而不是人们需要实际物品。
Uncaught Error: Objects are not valid as a React child
means you are trying to render an object in your jsx. Uncaught Error: Objects are not valid as a React child
意味着你正试图在你的 jsx 中呈现 object。 You can only render one property at at at time.您一次只能渲染一个属性。
<div>{user.username}</div>
{user.items.map((item)=>(
<div>{item}</div>
))
**assuming each "item" is one value (ie string or number etc..) **假设每个“项目”是一个值(即字符串或数字等)
Furthermore firestore updateDoc takes a ref as its first argument and the object as is second.此外,firestore updateDoc将 ref 作为其第一个参数,将 object 作为第二个参数。
You already have the ref usersRef
which I think a collection not a document, but I believe that firestore will add a document anyway, so just add the object (without any arrayUnion).你已经有了 ref usersRef
,我认为它是一个集合而不是一个文档,但我相信firestore 无论如何都会添加一个文档,所以只需添加 object(没有任何 arrayUnion)。 assuming items is an array then boom!假设 items 是一个数组然后繁荣!
// const usersRef = collection(firestore, "users")
await updateDoc(usersRef, { username: "yeah", items: items })
firestore will add an id automatically. firestore 会自动添加一个 id。
Technically you should be updating by getting a ref for a particular document first and using setDoc()
for creating从技术上讲,您应该首先通过获取特定文档的引用并使用setDoc()
来进行更新
const usersRef = collection(firestore, "users")
// This is create new document
const newDoc = await setDoc(usersRef, {username: "yeah", items: items})
// This will update only properties you include in the object
const userRef = doc(usersRef, {newDoc.id})
await updateDoc(usersRef, {items: newItems})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.