修复错误 [FirebaseError: 由于客户端离线而无法获取文档

问题描述 投票:0回答:1

我正在用你们的 firebase 开发一个应用程序。 我正在尝试保存并引用来自 cloud firestore 的一些数据。 我发现以下错误。 [FirebaseError:由于客户端离线而无法获取文档。] 我确认过了 1.网络环境 2.安全规则 3.防火墙 等等 你能帮我解决一下吗

import { initializeApp } from 'firebase/app';
// Optionally import the services that you want to use
import { getAuth } from "firebase/auth"
import { getDatabase }from "firebase/database";
import { getFirestore } from "firebase/firestore";
// import database from '@react-native-firebase/database';
// import {...} from "firebase/firestore";
// import {...} from "firebase/functions";
// import {...} from "firebase/storage";

// Initialize Firebase(there is no data due to private information)
const firebaseConfig = {
  apiKey: 
  authDomain: 
  databaseURL: 
  projectId: 
  storageBucket: ,
  messagingSenderId: ,
  appId: ,
  measurementId:
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
// Initialize Realtime Database and get a reference to the service
export const database = getDatabase(app);
// For more information on how to access Firebase in your project,
// see the Firebase documentation: https://firebase.google.com/docs/web/setup#access-firebase
export const firestore = getFirestore(app);
// https://firebase.google.com/docs/firestore/manage-data/add-data?hl=ja

import React, { useState, useEffect } from "react";
import { View,ActivityIndicator, Text, ScrollView, StyleSheet, TextInput, Button ,Switch,Dimensions,Image,Alert} from "react-native";
import { useNavigation } from '@react-navigation/native'; // useNavigationを追加
import MapView, { Marker ,Polyline} from 'react-native-maps';
import {requestLocationPermission,getCurrentLocation,writeMyLocationData} from '../../sockets/googlemap'
import {findPlace,fetchRoute} from '../../sockets/googleroute'
import { ref,onChildAdded} from "firebase/database";
import { database,firestore } from '../../firebaseConfig'; // Firebaseのデータベースを正しくインポートする必要があります
import { Input} from 'react-native-elements'; // React Native Elementsからボタンをインポート

import { doc, setDoc , collection, addDoc ,getDocs,getDoc} from "firebase/firestore"; 

const Main = () => {
    const [otherRiders, setOtherRiders] = useState([]); 
    const dbref = ref(database); //取得したいデータのパスを指定
    console.log("kakunin",otherRiders)
    const [routeInfo, setRouteInfo] = useState({ origin: "", destination: "" });
    const navigation = useNavigation(); // useNavigationフックを使用してnavigationオブジェクトを取得
    const [myCurrentLocation,setMyCurrentLocation] = useState({
        latitude: 0,
        longitude: 0,
    })
    const [myDestination,setMyDestination] = useState({
        latitude: 0,
        longitude: 0,
    })
    const [myOrigin,setMyOrigin] = useState({
        latitude: 0,
        longitude: 0,
    })
    // DB を取得している
    
    const [isMapReady, setIsMapReady] = useState(false);
    const [isEnabled, setIsEnabled] = useState(false);
    const toggleSwitch = () => setIsEnabled(previousState => !previousState);
    const iconImage = require('../../assets/kurumi.jpg');
    const myDestinationIcon = require('../../assets/flag.png');
    const myOriginIcon = require('../../assets/start.png');

    // requestLocationPermission();
    useEffect(() => {
        requestLocationPermission(setMyCurrentLocation,myCurrentLocation,setIsMapReady);
        const childAddedListener = onChildAdded(dbref, function (snapshot) {
        let data = snapshot.val();
        setOtherRiders(data);
    });
    const saveUserData = async () => {
        try {
        const docRef = await addDoc(collection(firestore, "users"), {
                name: "Tokyo",
                });
                console.log("Document written with ID: ", docRef.id);
            } catch (e) {
                console.error("エラーが発生しました:", e);
            } finally {
                console.log("保存が完了しました!");
            }
    };

    const fetchUserData = async () => {
        try {
// Query a reference to a subcollection
            const docRef = doc(firestore, "users", "FHNX6msuu6rOLjRGlalw");
            const docSnap = await getDoc(docRef);
            console.log("docSnap",docSnap)
        } catch (e) {
            console.error("エラーが発生しました:", e);
        } finally {
            console.log("しゅとく");
        }
    };
    saveUserData()
    fetchUserData(); // 非同期関数を呼び出す


    // const testt = async ()=>{
    //     // Add a new document with a generated id.
    //            console.log("ssssssssss")
        
    //     const docRef = await addDoc(collection(firestore, "users"), {
    //     name: "Tokyo",
    //     });
    //     console.log("Document written with ID: ", docRef.id);
    // }
    // test()
    // testt()
    return () => {
        // コンポーネントがアンマウントされたときにイベントリスナーを解除する
        childAddedListener();
    };
        
},[]);

    return (
        isMapReady ? ( // マップが準備完了したら表示
        <ScrollView  style={styles.Wrapper}>
            
                <View style={styles.mapContainer}>
                    <MapView style={styles.map}
                        initialRegion={{
                            latitude: myCurrentLocation.latitude,
                            longitude: myCurrentLocation.longitude,
                            latitudeDelta: 0.0922,
                            longitudeDelta: 0.0421,
                        }}
                    >
                        {/* <Marker
                            coordinate={{
                                latitude: myCurrentLocation.latitude,
                                longitude: myCurrentLocation.longitude,
                            }}
                        >
                            <Image style={styles.icon} source={iconImage} />
                        </Marker> */}
                    <Marker
                            coordinate={{
                                latitude: myOrigin.latitude,
                                longitude: myOrigin.longitude,
                            }}
                        >
                            <Image style={styles.icon} source={myOriginIcon} />
                        </Marker>
                        <Marker
                            coordinate={{
                                latitude: myDestination.latitude,
                                longitude: myDestination.longitude,
                            }}
                        >
                            <Image style={styles.icon} source={myDestinationIcon} />
                        </Marker>
                            <Polyline
                            coordinates={[
                                { latitude: myOrigin.latitude, longitude: myOrigin.longitude },
                                { latitude: myDestination.latitude, longitude: myDestination.longitude },
                            ]}
                            strokeColor="#FF0000" // 線の色
                            strokeWidth={2} // 線の太さ
                        />
                        {
                            otherRiders.map((rider,index)=>{
                                console.log("rider",rider)
                                let diferLat = Math.abs(myCurrentLocation.latitude - rider.latitude) < 1 ? true:false;
                                let diferLot = Math.abs(myCurrentLocation.longitude - rider.longitude) < 1 ? true:false;
                                // if(diferLat && diferLot){
                                //     Alert.alert("手を振りましょう")
                                // }
                        return(
                        <Marker
                            key={index} // ここで一意のキーを提供する
                            coordinate={{
                                latitude: rider.latitude,
                                longitude: rider.longitude,
                            }}
                        >
                            <Image style={styles.icon} source={iconImage} />
                        </Marker>

                        ) 
                            })
                        }


                    </MapView>
                </View>                
                <Text style={styles.direction}>出発地</Text>
                <Input
                    placeholder={'出発地を入力してください'}
                    value={routeInfo.origin}
                    onChangeText={text => setRouteInfo({ ...routeInfo, origin: text })}
                />
                <Text style={styles.direction}>目的地</Text>
                <Input
                    placeholder={'到着地を入力してください'}
                    value={routeInfo.destination}
                    onChangeText={text => setRouteInfo({ ...routeInfo, destination: text })}
                />
            <View>
                <Button
                    title="ルートを検索する"
                    onPress={() => fetchRoute(setMyOrigin,setMyDestination,routeInfo)}
                />
            </View>
            <View>
                <Button
                    title="戻る"
                    onPress={() => navigation.navigate('Top')}
                />
            </View>
        </ScrollView>
        ):  <View style={styles.waitContainer}><ActivityIndicator size="large" color="#0000ff" /><Text style={styles.waitText}>少々お待ちください...</Text></View>
    )
}

export default Main;

const { height } = Dimensions.get("window");
const mapHeight = height * 0.5; // 画面の半分の高さ
const styles = StyleSheet.create({
    Wrapper:{
        flex: 1, // 画面の半分のサイズに設定
    },
    direction: {
        fontSize: 12,
        padding:10
    },
    infomation: {
        fontSize: 12,
        padding:10
    },
    subTitle: {
        fontSize: 14,
        textAlign: "center",
        padding:5
    },
    mapContainer: {
        height: mapHeight,
        justifyContent: 'center',
        alignItems: 'center',
    },
    map: {
        ...StyleSheet.absoluteFillObject,
    },
    markerContainer: {
        backgroundColor: 'blue',
        padding: 5,
        borderRadius: 5,
    },
    markerText: {
        color: 'white',
        fontWeight: 'bold',
    },
    imputWrapper: {
        alignItems: "center", // 横方向に中央揃え
        padding: 20
    },
    imputContainer:{
        width:'100%',
        marginBottom:10
    },
    imputBox: {
        height: 40,
        borderWidth: 1,
    },
    icon: {
      width: 28,
      height: 28,
    },
    waitScrollViewContent: {
    flex: 1,
    width:'100%',
  },
    center: {
    flex: 1,
        justifyContent: 'center',
        alignItems: 'center',

    },
    waitContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    waitText: {
        marginTop: 10,
        fontSize: 16,
    },
});

1.网络环境 2.安全规则 3.防火墙

javascript reactjs firebase google-cloud-firestore expo
1个回答
0
投票

我将关闭这个问题。谢谢大家

© www.soinside.com 2019 - 2024. All rights reserved.