fusunnn
fusunnn

Reputation: 118

Trying to store FireStore array in React Native?

I have been trying to push or store a FireStore array in one of my own arrays. I have tried a few versions of code, the first being this:

var data = [];
  db.collection('Rooms')
    .doc(code)
    .get()
    .then((docs) => data.push(docs.data()));

However, when I log the data variable, it comes out as an empty array. The second method I have tried is this:

 var [data, setData] = useState([]);
  db.collection("Rooms")
    .doc(code)
    .get()
    .then((docs) => setData(docs.data()));

However this method seems to setData infinitely, so it is reading into my API infinitely, which I would like to avoid. The last method I tried was this:

  var data = db.collection("Rooms").doc(code).get();
  console.log(data);

But this just returns

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

Could anyone help me with this, ideally I'd like to store the data of an array called "MovieArray" inside the document, but I can't even access the document, so even if you can just help me store the data of the whole document, it would be very helpful.

Upvotes: 1

Views: 1216

Answers (2)

Dallas Baker
Dallas Baker

Reputation: 376

If you are using react, I would suggest using the hook. You also, don't really need to push objects to an array like that.

Here is an example of how to get some data and store the collection of data.

const Forum = () => {
  const [posts, setPosts] = useState(null);

  const collectIdsAndDocs = (doc) => {
    return { id: doc.id, ...doc.data() };
  };

  useEffect(() => {
    const getPost = async () => {
      const snapshot = await firestore.collection('Posts').get();
      const myPosts = snapshot.docs.map(collectIdsAndDocs);
      console.log(myPosts);
      setPosts({ myPosts });
    };

    const createPost = async (post) => {
      const docRef = await firestore.collection('Posts').add(post);
      const doc = await docRef.get();
      console.log(doc);
    };

    createPost({ Title: 'My First Post', Content: 'My content' });
    getPost();
  }, []);

  return (
    // return some JSX 
  );
};

Why does this work?

When you get a collection, Firebase returns a snapshot of the collection. This snapshot has a list of docs or an array if you will.

We then want to map over those docs constructing a new object that contains just the document data and the ID of individual doc. This is what the myPosts variable is.

Using the react state hook, you can set that object to the current state of Posts, in your case this would be rooms.

When you add something to the database, Firestore will return a reference to the newly added item. You can then call get() to get the document back if you need it.

Upvotes: 3

Suzuna Minami
Suzuna Minami

Reputation: 431

Try changing to (see comment before this)

const [data, setData] = useState({});

Upvotes: 0

Related Questions