import { Text, View, TextInput, Pressable, ScrollView } from 'react-native'; import {…
- 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?
- 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
setImageDataandConstants.platforminside the component.Try importing
Platformfromreact-nativeinstead of usingConstants.platform, and also make sure to check if theresponseobject fromImagePickeris notnullbefore 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.
- User
i found en err! launchImageLibraryAsync its correct
- Assistant
Ah, I see! That is definitely a mistake I missed. Good catch!
So, to fix the TypeError you mentioned earlier, you should replace
launchImageLibrarywithlaunchImageLibraryAsync. Here's the updatedchooseImagefunction: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.
- User
now it says property image doesnt exist
- Assistant
This error occurs because you're trying to upload an image to Firebase using
fetch(), but theimageDatayou pass to it doesn't have auriproperty. In fact, theimageDatareturned byImagePicker.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
uriinstead ofimageDatato fetch the binary data of the image and upload it to Firebase Storage.Here's an updated
addHandlerfunction 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
imageDatawithuriin thefetch()call. Also, since we're usingput()instead ofputString(), we don't need to specify the encoding type of the image data.Hope this solves the issue!
- 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?
- Assistant
Yes, your updated code looks good! You've added the
chooseImagefunction usinglaunchImageLibraryAsync, and changed the references toimageDatato useresult.uriinstead. However, there's one small issue in youraddHandlerfunction: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.
- User
it says err property image doesnt exist
- Assistant
This error occurs because the
imageDatavariable you're using in the component does not contain animageproperty.In the
addHandlerfunction, you're trying to accessimageData.urito fetch the image data, but sinceimageDatadoesn't have auriproperty, you get an error.To fix this, you should update your code to use the correct property name. Here's the updated
addHandlerfunction: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.urito fetch the image data and create aBlobobject. Then, we pass thisBlobobject toput()to upload it to Firebase Storage.Hope this solves the issue!
- 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
- Assistant
The warning message you're seeing is due to a recent change in the
ImagePickerAPI in the Expo SDK. In SDK 48 and later, theuriproperty of theImagePickerresult is deprecated and the selected image(s) should be accessed via theassetsarray instead.To fix the warning and future-proof your code, you should update your
chooseImagefunction to check for theassetsarray instead of theuriproperty. Here's an updated version of the function:const chooseImage = async () => {
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.