Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

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 ImagePicker from 'expo-image-picker';

    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); } }); }; 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 () => {
        const storageRef = firebase.storage().ref();
        const imageRef = storageRef.child(`images/${Date.now()}`);
        const uploadTask = imageRef.putFile(imageData.uri);
        uploadTask.on(
        'state_changed',
        null,
        (error) => {
        console.log(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
        })
    })}
    

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

    ); }

    i got en err TypeError: Cannot read property 'launchImageLibrary' of undefined, js engine: hermes

  2. Assistant

    This error occurs because the ImagePicker library is not properly imported and initialized. Make sure to import and initialize the ImagePicker library properly before using its launchImageLibrary method. Here's an example of how to import and initialize ImagePicker properly:

    import * as ImagePicker from 'expo-image-picker';
    import Constants from 'expo-constants';
    
    // Initialize the ImagePicker library
    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);
      });
    }
    

    Also, make sure that you are running your app on a real device or emulator that supports image picking. The launchImageLibrary method will not work on the web platform.

  3. User

    well now i have this TypeError: undefined is not a function, js engine: hermes

  4. Assistant

    The TypeError: undefined is not a function error occurs when you try to call a method or function on a value that is undefined. Here are some possible reasons for this error and how to fix them:

    1. Check if you properly initialized your Firebase application. Make sure to call firebase.initializeApp() before using any Firebase services.

    2. Verify that the firebase.storage() and firebase.database() methods are returning valid objects. You can use console.log() statements to check the values of these objects. If they are undefined, it could mean that you either have a typo or that the Firebase SDK is not properly integrated into your project.

    3. Verify that the uploadTask object has an on() method. If this method is missing, it could indicate that the putFile() method did not return a valid UploadTask object.

    Also, make sure to review your code and check for any syntactical errors, such as missing or extra commas, parentheses, or curly braces. It's possible that a syntax error is causing the undefined value.

    I hope this helps! If you still have issues, please share your relevant code snippet and any error messages you are seeing for a more accurate analysis.

  5. 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 () => {
        const storageRef = firebase.storage().ref();
        const imageRef = storageRef.child(`images/${Date.now()}`);
        const uploadTask = imageRef.putFile(imageData.uri);
        uploadTask.on(
        'state_changed',
        null,
        (error) => {
        console.log(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
        })
    })}
    

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

    ); }

    its my code

  6. Assistant

    Based on the code you provided, it looks like you are initializing the ImagePicker library properly using expo-image-picker, so that should not be causing the error.

    The issue seems to be with how you are retrieving the image data and passing it to the firebase.storage() method. Instead of using setImageData to set the state of your image data, you can use response.uri directly to upload the image to Firebase Storage.

    Here is an updated chooseImage function that should work for you:

    const chooseImage = async () => {
      try {
        const options = {
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          quality: 0.5,
        };
        const response = await ImagePicker.launchImageLibraryAsync(options);
        if (!response.cancelled) {
          const uri = response.uri;
          setImageData(uri);
        }
      } catch (error) {
        console.log("Error choosing image:", error);
      }
    };
    

    Then, to upload the image to Firebase Storage, you can use the putString method instead of putFile, like this:

    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);
      }
    };
    

    I hope this helps you resolve the error!

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