0

I am very new to React Native and I want to complete this in the most simple way possible, without navigation. I know how a ternary operator works, but the syntax may be wrong. My code is no longer giving an error.

This code should check if a user exists in firebase, run <Text> You are signed in <Text/> if there is a current user, and run the sign-in code otherwise. Thanks for helping.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

import * as firebase from 'firebase';

const firebaseConfig = {
    apiKey: /
    authDomain: /
    projectId: /
    storageBucket: /
    messagingSenderId: /
    appId: /
    measurementId: /
};

// if (!firebase.apps.length) {
//   firebase.initializeApp({});
// }else {
//   firebase.app(); // if already initialized, use that one
// }

firebase.initializeApp(firebaseConfig);
console.log("firebase init");

import {Container, Content, Header, Form, Input, Item, Button, Label, Image } from 'native-base'

export default class App extends React.Component {

  constructor(props){
    super(props)

    this.state =({
        email: '',
        password: '',
    })
  }

  signUpUser = (email, password) => {

    try{
      
      if(this.state.password.length<6){
        alert("Please enter at least 6 characters")
        return;
      }

      firebase.auth().createUserWithEmailAndPassword(email, password)

    }
    catch(error){
      console.log(error.toString())
    }
  }

  loginUser = (email, password) => {

    try{
      firebase.auth().signInWithEmailAndPassword(email,password).then(function (user){
        console.log(user) 
        })
    }
    catch(error){
      console.log(error.toString())
    }

  }

  render(){
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        <Text>You are signed in</Text>
      } else {
        <Container style={styles.container}>
            <Form>
                <Item floatingLabel>
                    <Label>Email</Label>
                    <Input 
                    autoCapitalize="none"
                    autoCorrect={false}
                    onChangeText={(email) => this.setState({email})}
                    />
                </Item>
                <Item floatingLabel>
                    <Label>Password</Label>
                    <Input 
                    secureTextEntry={true}
                    autoCapitalize="none"
                    autoCorrect={false}
                    onChangeText={(password) => this.setState({password})}
                    />
                </Item>
                <Button style={{marginTop: 50 }}
                  full
                  rounded
                  success
                  onPress={() => this.loginUser(this.state.email, this.state.password)}
                >
                  <Text style={{color: 'white'}} >Login</Text>
                </Button>
                <Button style={{marginTop: 10 }}
                  full
                  rounded
                  primary
                  onPress={() => this.signUpUser(this.state.email, this.state.password)}
                >
                  <Text style={{color: 'white'}}> Sign up</Text>
                </Button>
            </Form>
        </Container>
      }
    });
    // return (
    // );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent: 'center',
    padding: 20,
  },
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

You can't call asynchronous APIs inside the render method, like you're doing here:

  render(){
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        <Text>You are signed in</Text>
      } else {
        <Container style={styles.container}>
        ...

Instead you should call the asynchronous method elsewhere (on onComponentDidMount or a useEffect) and then set the user object into the state of the component.

See for an example of this:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hi, on every screen do i need to call `onAuthStateChanged` to check if a user is signed or do i call it on my WelcomeScreen and store it in async storage to be able to access it globally? – kd12345 Mar 09 '23 at 10:15
  • 1
    Firebase will already stores the credentials/token in local storage, so calling `onAuthStateChanged` on every screen will just get it from there anyway. – Frank van Puffelen Mar 09 '23 at 14:15