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

my auth in react native expo firebase isnt working. here is my code import { Text, View,…

  1. User

    my auth in react native expo firebase isnt working. here is my code import { Text, View, TextInput, Pressable, ScrollView, Alert } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { useNavigation } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; import React, {useState} from ‘react’;

    export default function Auth() { const navigation = useNavigation(); const [email, setEmail] = useState(‘’); const [phone, setPhone] = useState(‘’); const [password, setPassword] = useState(‘’); const [errorMessage, setErrorMessage] = React.useState(null); const handleLogin=()=>{ if (!email || !password) { Alert.alert(‘Ошибка!’,‘Неверная почта или пароль’); return; } firebase.auth().currentUser.getIdToken().signInWithEmailAndPassword(email, password) .then(()=>{ navigation.navigate(‘Profile’); }) .catch((error)=>{ setErrorMessage(error.message); console.log(error); }) } return (

    Войти в личный{“\n”}кабинет Почта Пароль Забыли пароль? Войти <Pressable onPress={()=>navigation.navigate(‘Registration’)}

    Я не зарегистрирован(а)

    i tried to add token but here is an err TypeError: Cannot read property ‘getIdToken’ of null, js engine: hermes

  2. Assistant

    It seems like you're trying to call the getIdToken() method on the current user object before the user has even been authenticated. You should only call this method after the user has been authenticated successfully.

    Here's what you can do to fix this:

    1. Remove the line firebase.auth().currentUser.getIdToken()
    2. Inside the handleLogin function, after the user is successfully authenticated, you can call firebase.auth().currentUser.getIdToken() to get the user's ID token.

    So your modified handleLogin function should look something like this:

    const handleLogin = () => {
      if (!email || !password) {
        Alert.alert('Ошибка!', 'Неверная почта или пароль');
        return;
      }
      
      firebase.auth().signInWithEmailAndPassword(email, password)
        .then(() => {
          const user = firebase.auth().currentUser;
          user.getIdToken()
            .then((token) => {
              // do something with the token
            })
            .catch((error) => {
              console.log(error);
            });
          navigation.navigate('Profile');
        })
        .catch((error) => {
          setErrorMessage(error.message);
          console.log(error);
        });
    };
    

    Note: Make sure to handle any errors that might occur while getting the token.

  3. User

    [FirebaseError: Firebase: A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred. (auth/network-request-failed).]

  4. Assistant

    This error message indicates that there was a problem with the network connection between your app and the authentication server. Firebase couldn't complete the network request to authenticate the user due to network issues such as a timeout, interrupted connection or an unreachable host.

    Here are some things you can try:

    1. Check your internet connection: Make sure your device or emulator is connected to the internet. You can try accessing other websites or online services to confirm that there isn't an issue with your internet connection.

    2. Check if Firebase is operational: Sometimes Firebase services may be down for maintenance or other issues. You can check if Firebase is operational by visiting the Firebase status page.

    3. Check if the Firebase API key is correct: Make sure that you have entered the correct Firebase API key in your React Native app. You can find this in your Firebase console.

    4. Retry later: If the issue persists, try again later. Sometimes the issue might be temporary and can be resolved by retrying later.

    Hope this helps!

  5. User

    when i try to registr user it says cannot read property uid of null here is my registration import { Text, View, Pressable, TextInput, Alert, ScrollView} from 'react-native'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { gStyle } from '../styles/style'; import React, {useState} from 'react'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import { useNavigation } from '@react-navigation/native';

    export default function Registration() { const navigation = useNavigation(); const [name, setName] = useState(''); const [surname, setSurname]=useState(''); const [email, setEmail] = useState(''); const [phone, setPhone] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword]=useState(''); const handleRegistration=()=>{ if( name===''|| surname===''|| email===''|| phone===''|| password===''|| confirmPassword==='' ){ Alert.alert('Ошибка!','Пожалуйста, заполните все поля для регистрации'); } if(password!==confirmPassword){ Alert.alert('Ошибка!','Пароли не совпадают'); return; } firebase.auth() .createUserWithEmailAndPassword(email, password) .then((result)=>{ const userDetails={ name, surname, email, phone, }; firebase.database().ref(users/${result.user.uid}).set(userDetails); }) } const onPressRegistration=async()=>{ try{ const userDetails=await handleRegistration(); navigation.navigate('Profile'); }catch(error){ Alert.alert('Ошибка!','Регистрация не прошла успешно'); }; } return ( Зарегистрироваться Имя <TextInput style={gStyle.RegInfo} onChangeText={text => setName(text)}/> Фамилия <TextInput style={gStyle.RegInfo} onChangeText={text => setSurname(text)}/> Электронная почта <TextInput style={gStyle.RegInfo} onChangeText={text => setEmail(text)}/> Номер телефона <TextInput style={gStyle.RegInfo} onChangeText={text => setPhone(text)}/> Пароль <TextInput style={gStyle.RegInfo} onChangeText={text => setPassword(text)} secureTextEntry={true}/> Подтверждение пароля <TextInput style={gStyle.RegInfo} onChangeText={text => setConfirmPassword(text)} secureTextEntry={true}/> Зарегистрироваться Нажимая на кнопку, Вы соглашаетесь с{'\n'}Политикой конфиденциальности ); };

  6. Assistant

    It seems like the handleRegistration function that you're calling within onPressRegistration doesn't return anything, which is causing the userDetails object to be null. Therefore, when you try to access the uid property of result.user, result.user is null, causing the error.

    To fix this, you can modify the handleRegistration function to return the userDetails object. Then, you can use this object after the user has been successfully authenticated to store the user's information in your Firebase Realtime Database.

    Here's how you can modify the handleRegistration function:

    const handleRegistration = async () => {
      if (
        name === '' ||
        surname === '' ||
        email === '' ||
        phone === '' ||
        password === '' ||
        confirmPassword === ''
      ) {
        Alert.alert('Ошибка!', 'Пожалуйста, заполните все поля для регистрации');
        return null;
      }
      if (password !== confirmPassword) {
        Alert.alert('Ошибка!', 'Пароли не совпадают');
        return null;
      }
      try {
        await firebase.auth().createUserWithEmailAndPassword(email, password);
        const userDetails = {
          name,
          surname,
          email,
          phone,
        };
        return userDetails;
      } catch (error) {
        setErrorMessage(error.message);
        return null;
      }
    };
    

    Also, modify the onPressRegistration function to check if the userDetails object isn't null before navigating to the Profile screen:

    const onPressRegistration = async () => {
      try {
        const userDetails = await handleRegistration();
        if (userDetails) {
          firebase.database().ref(`users/${firebase.auth().currentUser.uid}`).set(userDetails);
          navigation.navigate('Profile');
        }
      } catch (error) {
        Alert.alert('Ошибка!', 'Регистрация не прошла успешно');
      }
    };
    

    This way we make sure that the userDetails object is not null and the user has been successfully created.

  7. User

    yess!! it works! u r super! no! megaultradupersuper!

  8. Assistant

    I'm glad to hear that it works! Don't hesitate to ask if you have any more questions or issues. Have a great day ahead! :)

  9. User

    how to create a table in firebase FutureMK with fields (id, name, description, price, time, timeOfMK, person and image)? and here is my code where admin can add this FutureMK import { Text, View, TextInput, Pressable, ScrollView } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState} from 'react'; import Footer from '../components/Footer'; import Header from '../components/Header'; //import { Formik } from 'formik'; //add header & footer export default function FormAddMK() { const [text, setValue] = useState(''); const onChange=(text)=>{ setValue(text); }; return ( Добавить мастер-класс Название мастер-класса Дата мастер-класса Описание мастер-класса Изображение Стоимость мастер-класса Кол-во людей на бронирование Продолжительность мастер-класса <Pressable style={gStyle.btnAddMK} onPress={()=>addHandler(text)}> Сохранить

    ); }

  10. Assistant

    To create a table named FutureMK in Firebase Realtime Database that has fields id, name, description, price, time, timeOfMK, person, and image, you can follow these steps:

    1. Go to the Firebase console, select your project, and then select the "Database" option from the left-hand navigation menu.

    2. From the Database tab, select "Realtime Database" and then choose "Create Database".

    3. Select "Start in test mode" and then click on "Enable".

    4. In the "Data" tab of the Realtime Database, click on the "+ Add Collection" button and give a name to the collection (in this case, you can name it "FutureMK" for example).

    5. Add fields to this collection using the "Add Field" button. Add fields id, name, description, price, time, timeOfMK, person, and image as described.

    6. Save the changes to create the "FutureMK" collection with the specified fields.

    Now when you add a new document to this collection, it will have the specified fields.

    Here's an example of how you can add a new document to this collection in your React Native app:

    import { firebase } from '../Firebase/firebase';
    
    function addHandler(text) {
      firebase.database().ref('FutureMK').push({
        id: 'some_id',
        name: text,
        description: 'some_description',
        price: 10,
        time: 'some_time',
        timeOfMK: 'some_timeOfMK',
        person: 5,
        image: 'some_image_url'
      });
    }
    

    In this example, we have created a function addHandler that calls the push() method on the Firebase database reference to add a new document to the "FutureMK" collection with the specified fields.

    Note that you should adjust the values of these fields based on your requirements and use cases.

  11. User

    how can i add image in the form so it saves to the collection of this?

  12. Assistant

    To upload an image file to Firebase Storage and then save its download URL to the Firebase Realtime Database collection for "FutureMK" that you created earlier, you can follow these steps:

    1. Import firebase/storage into your file to use the Firebase Storage API.

    2. Include an <input> element of type file in your form that allows the user to select an image file.

    3. In your addHandler function, get a reference to the Firebase Storage bucket and create a unique filename for the image file based on a timestamp or other unique identifier.

    4. Upload the image file to Firebase Storage using the put() method and the selected file object.

    5. After the image file has been uploaded successfully, get the download URL of the file using the getDownloadURL() method and save it to the corresponding "FutureMK" document in the Firebase Realtime Database.

    Here's an example of how you can modify your FormAddMK component to include an image upload functionality and update your addHandler function accordingly:

    import { Text, View, TextInput, Pressable, ScrollView } from 'react-native';
    import { gStyle } from '../styles/style';
    import React, { useState } from 'react';
    import Footer from '../components/Footer';
    import Header from '../components/Header';
    import { firebase } from '../Firebase/firebase';
    import 'firebase/compat/storage';
    
    export default function FormAddMK() {
        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.put(image);
          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,
    

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