Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

import { Text, View, TextInput, Pressable, ScrollView } from 'react-native'; import {…

  1. User

    import { Text, View, TextInput, Pressable, ScrollView } from 'react-native'; import { gStyle } from '../styles/style'; import Footer from '../components/Footer'; import Header from '../components/Header'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; import * as ImagePicker from 'expo-image-picker'; import Constants from 'expo-constants';

    export default function FormAddMK() { const [imageData, setImageData] = useState(null); const chooseImage = () => { const options = { mediaType: 'photo', quality: 0.5, }; ImagePicker.launchImageLibrary(options, (response) => { if (response.uri) { setImageData(response); } }); }; if (Constants.platform.ios || Constants.platform.android) { ImagePicker.requestMediaLibraryPermissionsAsync().then(() => { console.log('Media permissions have been granted.'); }).catch((error) => { console.log('Error getting media permissions:', error); }); } const [text, setValue] = useState(''); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [price, setPrice] = useState(''); const [time, setTime] = useState(''); const [timeOfMK, setTimeOfMK] = useState(''); const [person, setPerson] = useState(''); const [image, setImage] = useState(null);

    const onChangeName = (text) => setName(text);
    const onChangeDescription = (text) => setDescription(text);
    const onChangePrice = (text) => setPrice(text);
    const onChangeTime = (text) => setTime(text);
    const onChangeTimeOfMK = (text) => setTimeOfMK(text);
    const onChangePerson = (text) => setPerson(text);
    const onChangeImage = (event) => {
    const file = event.target.files[0];
    setImage(file);
    };
    const addHandler = async () => {
        try {
        const storageRef = firebase.storage().ref();
        const imageRef = storageRef.child(`images/${Date.now()}`);
        const response = await fetch(imageData);
        const blob = await response.blob();
        const uploadTask = imageRef.putString(blob, 'data_url');
        uploadTask.on(
        'state_changed',
        null,
        (error) => {
        console.log('Error uploading image:', error);
        },
        async () => {
        const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
        firebase
        .database()
        .ref('FutureMK')
        .push({
        id: Date.now(),
        name: name,
        description: description,
        price: price,
        time: time,
        timeOfMK: timeOfMK,
        person: person,
        image: downloadURL,
        });
        }
        );
        } catch (error) {
        console.log('Error adding MK:', error);
        }
        };
    

    return ( Добавить мастер-класс Название мастер-класса Дата мастер-класса Описание мастер-класса Изображение {imageData ? ( <Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} /> ) : null} Выбрать изображение Стоимость мастер-класса Кол-во людей на бронирование Продолжительность мастер-класса Сохранить

    ); }

    but i have an err TypeError: undefined is not a function, js engine: hermes what did i do wrong?

  2. Assistant

    It's difficult to determine the exact issue without seeing the full error message and the line number where the error occurred. However, one possible issue could be related to the way you're using setImageData and Constants.platform inside the component.

    Try importing Platform from react-native instead of using Constants.platform, and also make sure to check if the response object from ImagePicker is not null before accessing its properties. Here's an updated code snippet with these changes:

    import { Text, View, TextInput, Pressable, ScrollView, Platform } from 'react-native'; // import Platform
    import { gStyle } from '../styles/style';
    import Footer from '../components/Footer';
    import Header from '../components/Header';
    import { firebase } from '../Firebase/firebase';
    import 'firebase/compat/auth';
    import 'firebase/compat/database';
    import 'firebase/compat/firestore';
    import React, { useState } from 'react'; // remove useEffect and useNavigation
    import * as ImagePicker from 'expo-image-picker';
    // remove Constants import
    
    export default function FormAddMK() {
        const [imageData, setImageData] = useState(null);
        const chooseImage = () => {
            const options = {
                mediaType: 'photo',
                quality: 0.5,
            };
            ImagePicker.launchImageLibrary(options, (response) => {
                if (response && response.uri) { // add null check for response
                    setImageData(response);
                }
            });
        };
        if (Platform.OS !== 'web') { // use Platform.OS instead of Constants.platform
            ImagePicker.requestMediaLibraryPermissionsAsync().then(() => {
                console.log('Media permissions have been granted.');
            }).catch((error) => {
                console.log('Error getting media permissions:', error);
            });
        }
    
        // rest of the component code unchanged
    }
    

    If this doesn't solve the issue, please provide more details about the error message and the line number where it occurred.

  3. User

    i found en err! launchImageLibraryAsync its correct

  4. Assistant

    Ah, I see! That is definitely a mistake I missed. Good catch!

    So, to fix the TypeError you mentioned earlier, you should replace launchImageLibrary with launchImageLibraryAsync. Here's the updated chooseImage function:

    const chooseImage = async () => { // add async/await
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); // move permission request to this function
        if (status !== 'granted') {
            console.log('Permission to access media library was denied')
            return; // exit the function if permission is not granted
        }
        const options = {
            mediaType: ImagePicker.MediaTypeOptions.Images,
            quality: 0.5,
        };
        let result = await ImagePicker.launchImageLibraryAsync(options); // use launchImageLibraryAsync
        if (!result.cancelled) { // check if the user selected an image
            setImageData(result);
        }
    };
    

    Hope this helps! Let me know if you have any other questions.

  5. User

    now it says property image doesnt exist

  6. Assistant

    This error occurs because you're trying to upload an image to Firebase using fetch(), but the imageData you pass to it doesn't have a uri property. In fact, the imageData returned by ImagePicker.launchImageLibraryAsync() is an object with the following properties:

    {
      cancelled: boolean, // true if the user cancelled the action
      type: string, // MIME type of the selected media
      uri: string, // local URI of the selected media
      width: number, // width of the selected media in pixels
      height: number, // height of the selected media in pixels
      ...
    }
    

    Therefore, you should use uri instead of imageData to fetch the binary data of the image and upload it to Firebase Storage.

    Here's an updated addHandler function that should work:

    const addHandler = async () => {
        try {
            const storageRef = firebase.storage().ref();
            const imageRef = storageRef.child(`images/${Date.now()}`);
    
            const response = await fetch(uri);
            const blob = await response.blob();
            
            const uploadTask = imageRef.put(blob);
            uploadTask.on(
                'state_changed',
                null,
                (error) => {
                    console.log('Error uploading image:', error);
                },
                async () => {
                    const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
                    
                    firebase
                        .database()
                        .ref('FutureMK')
                        .push({
                            id: Date.now(),
                            name: name,
                            description: description,
                            price: price,
                            time: time,
                            timeOfMK: timeOfMK,
                            person: person,
                            image: downloadURL,
                        });
                }
            );
        } catch (error) {
            console.log('Error adding MK:', error);
        }
    };
    

    Note that you now need to replace imageData with uri in the fetch() call. Also, since we're using put() instead of putString(), we don't need to specify the encoding type of the image data.

    Hope this solves the issue!

  7. User

    import { Text, View, TextInput, Pressable, ScrollView } from 'react-native'; import { gStyle } from '../styles/style'; import Footer from '../components/Footer'; import Header from '../components/Header'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState,} from 'react'; import * as ImagePicker from 'expo-image-picker';

    export default function FormAddMK() { const [imageData, setImageData] = useState(null); const chooseImage = async() => { const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (status !== 'granted') { console.log('Permission to access media library was denied') return; // exit the function if permission is not granted } const options = { mediaType: ImagePicker.MediaTypeOptions.Images, quality: 0.5, }; let result = await ImagePicker.launchImageLibraryAsync(options); // use launchImageLibraryAsync if (!result.canceled) { // check if the user selected an image setImageData(result); } };

    if (Platform.OS !== 'web') { // use Platform.OS instead of Constants.platform
    ImagePicker.requestMediaLibraryPermissionsAsync().then(() => {
    console.log('Media permissions have been granted.');
    }).catch((error) => {
    console.log('Error getting media permissions:', error);
    });
    }
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [price, setPrice] = useState('');
    const [time, setTime] = useState('');
    const [timeOfMK, setTimeOfMK] = useState('');
    const [person, setPerson] = useState('');
    const [image, setImage] = useState(null);
    
    const onChangeName = (text) => setName(text);
    const onChangeDescription = (text) => setDescription(text);
    const onChangePrice = (text) => setPrice(text);
    const onChangeTime = (text) => setTime(text);
    const onChangeTimeOfMK = (text) => setTimeOfMK(text);
    const onChangePerson = (text) => setPerson(text);
    const onChangeImage = (event) => {
    const file = event.target.files[0];
    setImage(file);
    };
    const addHandler = async () => {
        try {
        const storageRef = firebase.storage().ref();
        const imageRef = storageRef.child(`images/${Date.now()}`);
        const response = await fetch(uri);
        const blob = await response.blob();
        const uploadTask = imageRef.put(blob);
        uploadTask.on(
        'state_changed',
        null,
        (error) => {
        console.log('Error uploading image:', error);
        },
        async () => {
        const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
        firebase
        .database()
        .ref('FutureMK')
        .push({
        id: Date.now(),
        name: name,
        description: description,
        price: price,
        time: time,
        timeOfMK: timeOfMK,
        person: person,
        image: downloadURL,
        });
        }
        );
        } catch (error) {
        console.log('Error adding MK:', error);
        }
        };
    

    return ( Добавить мастер-класс Название мастер-класса Дата мастер-класса Описание мастер-класса Изображение {imageData ? ( <Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} /> ) : null} Выбрать изображение Стоимость мастер-класса Кол-во людей на бронирование Продолжительность мастер-класса Сохранить

    ); }

    like this?

  8. Assistant

    Yes, your updated code looks good! You've added the chooseImage function using launchImageLibraryAsync, and changed the references to imageData to use result.uri instead. However, there's one small issue in your addHandler function:

    const response = await fetch(uri);
    

    You're using the variable uri, but it hasn't been defined in your component. To fix this, you need to change this line to:

    const response = await fetch(imageData.uri);
    

    This will fetch the binary data of the image selected by the user.

    Other than that, everything else looks good! Let me know if you have any other issues.

  9. User

    it says err property image doesnt exist

  10. Assistant

    This error occurs because the imageData variable you're using in the component does not contain an image property.

    In the addHandler function, you're trying to access imageData.uri to fetch the image data, but since imageData doesn't have a uri property, you get an error.

    To fix this, you should update your code to use the correct property name. Here's the updated addHandler function:

    const addHandler = async () => {
        try {
            const storageRef = firebase.storage().ref();
            const imageRef = storageRef.child(`images/${Date.now()}`);
            const response = await fetch(imageData.uri);
            const blob = await response.blob();
            const uploadTask = imageRef.put(blob);
            uploadTask.on(
                'state_changed',
                null,
                (error) => {
                    console.log('Error uploading image:', error);
                },
                async () => {
                    const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
                    firebase
                        .database()
                        .ref('FutureMK')
                        .push({
                            id: Date.now(),
                            name: name,
                            description: description,
                            price: price,
                            time: time,
                            timeOfMK: timeOfMK,
                            person: person,
                            image: downloadURL,
                        });
                }
            );
        } catch (error) {
            console.log('Error adding MK:', error);
        }
    };
    

    Here, we're using imageData.uri to fetch the image data and create a Blob object. Then, we pass this Blob object to put() to upload it to Firebase Storage.

    Hope this solves the issue!

  11. User

    it says key uri in the image picker result is deprecated and will be removed in sdk 48, you can access selected assets through the assets array instead

  12. Assistant

    The warning message you're seeing is due to a recent change in the ImagePicker API in the Expo SDK. In SDK 48 and later, the uri property of the ImagePicker result is deprecated and the selected image(s) should be accessed via the assets array instead.

    To fix the warning and future-proof your code, you should update your chooseImage function to check for the assets array instead of the uri property. Here's an updated version of the function:

    const chooseImage = async () => {
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.