React Native - загрузка файлов с проблемой firestore - TypeError: e.addEventListener не является функцией - PullRequest
0 голосов
/ 06 мая 2020

Пытаюсь закачать файлы через firestore. Хотя для фотографий он работает на консоли firebase, у меня уже такая же проблема. У меня есть unistall и переустановка библиотек firebase, но это не работает. Я не знаю, откуда взялась эта ошибка. Пожалуйста, предложите мне правильное решение, заранее спасибо.

это то, что отображается] 1

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Image, TextInput } from 'react-native';
import {Ionicons} from '@expo/vector-icons';
import Contants from "expo-constants";
import * as Permissions from "expo-permissions";
import Fire from "../Fire";
import * as ImagePicker from "expo-image-picker";
import 'firebase/firestore';

const firebase = require('firebase');
require("firebase/firestore");

export default class PostScreen extends React.Component {
    state = {
        text: "",
        
    };

    componentDidMount() {
        this.getPhotoPermission();
    }

    getPhotoPermission = async () => {
        if (Contants.platform.ios) {
            const {status} = await Permissions.askAsync(Permissions.CAMERA_ROLL)
            if (status != "granted") {
                alert("Nous avons besoin d'acceder à votre camera");
            }
        }
    };
 
    handlePost = () => {
        Fire.shared
            .addPost({ text: this.state.text.trim(), localUri: this.state.image })
            .then(ref => {
                this.setState({text: "", image: null});
                this.props.navigation.goBack();
        })
            .catch(error => {
                alert(error);
        });
    };

    pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3]
        });

        if (!result.cancelled) {
            this.setState({ image: result.uri });
        }
    }
    render() {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
                        <Ionicons name="md-arrow-back"  size={24} color="#D8D9DB">
 
                        </Ionicons>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this.handlePost}>
                        <Text style={{ fontWeight: "500"}}>
                            Post
                        </Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.inputContainer}>
                    <Ionicons name="ios-add-circle" size={45} style={styles.avatar}/>
                    <TextInput 
                    autoFocus={true} 
                    multiline={true} 
                    numberOfLines={4} 
                    style={{ flex: 1 }} 
                    placeholder="Voulez-vous ajouter un nouveau plat ?"
                    onChangeText={text => this.setState({text})}
                    value={this.state.text}>

                    </TextInput>      
                </View>

                <TouchableOpacity style={styles.photo}onPress={this.pickImage}>
                    <Ionicons name="md-camera" size={32} color= "#000" />
                </TouchableOpacity>

                <View style={{ marginHorizontal: 32, marginTop: 32, height: 150 }} >
                    <Image source={{ uri: this.state.image }} style={{ width: "100%", height: "100%" }} />
                </View>
               
            </SafeAreaView>
        );
    }
}
const styles = StyleSheet.create ({
    container: {
        flex: 1,
        marginBottom: 12
       
    },
    header: {
        flexDirection: "row",
        justifyContent: "space-between",
        paddingHorizontal: 32,
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: "#D8D9DB"
    },
    inputContainer: {
        margin: 32,
        flexDirection: "row"
    },
    avatar: {
        width: 48,
        height: 48,
        borderRadius: 24,
        marginRight: 16,
        
    },
    photo: {
        alignItems: "flex-end",
        marginHorizontal: 32   
    },
});
export default FirebaseKeys = {
    
        apiKey: "********",
    authDomain: "*********",
    databaseURL: "********",
    projectId: "**********",
    storageBucket: "******",
    messagingSenderId: "**",
    appId: "**************",
    measurementId: "******"
  };
import FirebaseKeys from "./config";
import firebase from "firebase";
import "@firebase/firestore";

class Fire {
    constructor() {
        firebase.initializeApp(FirebaseKeys);
        
    }

    addPost = async ({ text, localUri }) => {
        const remoteUri = await this.uploadPhotoAsync(localUri);

        return new Promise((res, rej) => {
            this.firestore
                .collection("posts")
                .add({
                    text,
                    uid: this.uid,
                    timestamp: this.timestamp,
                    image: remoteUri
                })
                .then(ref => {
                    res(ref);
                })
                .catch(error => {
                    rej(error);
                });
        });
    };

    uploadPhotoAsync = async uri => {
        const path = `photos/${this.uid}/${Date.now()}.jpg`

         return new Promise(async (res, rej) => {
            const response = await fetch(uri);
            const file = await response.blob();

            let upload = firebase
                .storage()
                .ref(path)
                .put(file);

            upload.on(
                "state_changed",
                snapshot => {},
                err => { 
                    rej(err);
                },
                async () => {
                    const url = await upload.snapshot.ref.getDownloadURL();
                    res(url);
                }
            );
        });
    };

    get firestore() {
        return firebase.firestore();
    }
    get uid() {
        return (firebase.auth().currentUser || {}).uid;
    }
    get timestamp() {
        return Date.now();
    }
}

Fire.shared = new Fire();
export default Fire;
...