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.
JavaScript
x
34
34
1
import React, { useEffect, useRef, useState } from "react";
2
import { Alert,FlatList,RefreshControl,StatusBar,Text,View } from "react-native";
3
import { TouchableOpacity } from "react-native-gesture-handler";
4
import styles from "./styles";
5
import { getDevices } from "../../services/devices";
6
import { useNavigation } from "@react-navigation/native";
7
import { Feather } from "@expo/vector-icons";
8
import CircularProgress from "react-native-circular-progress-indicator";
9
import { removeDevice } from "../../redux/actions";
10
import { useDispatch } from "react-redux";
11
import firebase from "firebase/app";
12
import "firebase/firestore";
13
14
const wait = (timeout) => {
15
return new Promise((resolve) => setTimeout(resolve, timeout));
16
};
17
18
export default function DevicesScreen() {
19
const [devices, setDevices] = useState([]);
20
const [loading, setLoading] = useState(false);
21
const componentMounted = useRef(true);
22
const navigation = useNavigation();
23
24
useEffect(() => {
25
getDevices().then(setDevices)
26
},[]);
27
console.log()
28
29
30
TypeError: undefined is not an object (evaluating '(0, _devices.getDevices)().then')
31
32
This error is located at:
33
in DevicesScreen (created by SceneView)
34
This error appears. If I remove .then(setDevices) I can see the array of data on the console.log
JavaScript
1
19
19
1
import firebase from "firebase/app";
2
import "firebase/firestore";
3
4
export const getDevices = () => {
5
firebase
6
.firestore()
7
.collection("device")
8
.where("user_id", "==", "Rweeff9MO8XIDheZLx0HVbfaezy2")
9
.get()
10
.then((querySnapshot) => {
11
querySnapshot.docs.map(doc => {
12
let data =doc.data();
13
console.log(data);
14
return { id, doc };
15
}
16
)}
17
)
18
}
19
Thanks
Advertisement
Answer
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:
JavaScript
1
11
11
1
export const getDevices = () => {
2
return admin // <========= See the return here
3
.firestore()
4
.collection("projects")
5
.get()
6
.then((querySnapshot) => {
7
return querySnapshot.docs.map(doc => ({ id: doc.id, doc.data() }));
8
// ^^^ See the return here
9
});
10
}
11