I'm new to React-Native and I am trying to return the array of data from the firstore query to the device screen where I can setDevices. I had this working using .get() and .then(), but I wasn't getting the updated events, so I've moved to onSnapshot and seem to have data at the query end, but can't get this set at the screen.
import React, { useEffect, useRef, useState } from "react";
import { Alert,FlatList,RefreshControl,StatusBar,Text,View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import styles from "./styles";
import { getDevices } from "../../services/devices";
import { useNavigation } from "@react-navigation/native";
import { Feather } from "@expo/vector-icons";
import CircularProgress from "react-native-circular-progress-indicator";
import { removeDevice } from "../../redux/actions";
import { useDispatch } from "react-redux";
import firebase from "firebase/app";
import "firebase/firestore";
const wait = (timeout) => {
return new Promise((resolve) => setTimeout(resolve, timeout));
};
export default function DevicesScreen() {
const [devices, setDevices] = useState([]);
const [loading, setLoading] = useState(false);
const componentMounted = useRef(true);
const navigation = useNavigation();
useEffect(() => {
getDevices().then(setDevices)
},[]);
console.log()
TypeError: undefined is not an object (evaluating '(0, _devices.getDevices)().then')
This error is located at:
in DevicesScreen (created by SceneView)
This error appears. If I remove .then(setDevices) I can see the array of data on the console.log
import firebase from "firebase/app";
import "firebase/firestore";
export const getDevices = () => {
firebase
.firestore()
.collection("device")
.where("user_id", "==", "Rweeff9MO8XIDheZLx0HVbfaezy2")
.get()
.then((querySnapshot) => {
querySnapshot.docs.map(doc => {
let data =doc.data();
console.log(data);
return { id, ...doc };
}
)}
)
}
Thanks
CodePudding user response:
There are several problems in your code.
- You don't return the Promises chain.
id
is not defined. You need to dodoc.id
.
So the following should do the trick:
export const getDevices = () => {
return admin // <========= See the return here
.firestore()
.collection("projects")
.get()
.then((querySnapshot) => {
return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// ^^^ See the return here
});
}