Search code examples
react-nativeauthenticationreact-native-navigationreact-native-router-flux

How can i do authenticate and navigate to main page in react native?


I am a new member of React Native and i stuck :)

I need to login to the main screen(Anaekran.js) with the correct mail and password. I get mail and password information from API.

When I press the button(MyButton), I expect the code to check the mail and password and redirect to the main screen(Anaekran.js) if it is correct, but nothing happens. I couldn't find the problem or problems. l really appreciate any help you can provide. I will return immidately for your answers and questions.

I used the router flux for navigating process. I don't share the Anaekran.js because i don't think we need Anaekran.js right now.

Some method,file names are Turkish.

This is LoginSayfasi.js (login page).

import React, {Component} from 'react';
import {View,Alert} from 'react-native';
import Input from '../components/Input';
import MyButton from '../components/MyButton';
import {Actions} from 'react-native-router-flux';

import {
    isLogin
} from '../components/Index';

import { serializeKey, setSessionTicket } from '../components/Index'

export default class LoginSayfasi extends Component {
  constructor(props) {
    super(props);
    this.isLoginControl();
    this.state = {
      mail: '',
      password: '',
    };
  }
  async isLoginControl() {
        var present = this;
        isLogin().then((res) => {
            if (res)
                Actions.Anaekran({type: 'reset'}); 
            else 
                Actions.LoginSayfasi({type: 'reset'});
        })
  }
  Giris() {
    var name = this.state.mail;
        var pass = this.state.password;
        if (name == "" || pass == "") {
            Alert.alert("You have to fill ");
        } else {
            fetch('192.168.1.14/rest/signin', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: serializeKey({
                    mail: name,
                    password: pass
                })
            })
            .then((res) => res.json()) 
        .then((res) => {
        if (res.session_ticket)
          setSessionTicket(String(res.session_ticket));
            if (res.status != -1)
        Actions.Anaekran({type: 'reset'});
            else
                Alert.alert("User could not be verified");
        })
            .catch((err) => {
                Alert.alert("There is a problem here! " + err);
            })
        }
  }
  render() {
    return (
      <View>
        <Input
          placeholder="Mail"
          autoCapitalize="none"
          onSubmitEditing={() => this.passwordInput.focus()}
          onChangeText={(value) => this.setState({mail : value})}
          value={this.state.mail}
          keyboardType={'email-address'}
        />
        <Input
          placeholder="Password"
          secureTextEntry={true}
          inputRef={input => (this.passwordInput = input)}
          onChangeText={(value) => this.setState({password : value})}
          value={this.state.password}
        />
        <MyButton
          textColor={'#f1f1f1'}
          text={'Sign In'}
          bgColor={'#0065e0'}
          onPress={this.Giris.bind(this)}
        />
      </View>
    );
  }
}

Login.js

import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  Text,
  KeyboardAvoidingView
} from 'react-native';
import LoginSayfasi from '../ekranlar/LoginSayfasi';

export default class Login extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.headBackground} />
        <KeyboardAvoidingView behavior={'position'}>
          <View>
            <Text style={styles.text1}>BLA BLA</Text>
            <Text style={styles.text2}>BLAAAA</Text>
          </View>
          <View style={styles.loginArea}>
            <LoginSayfasi />
          </View>
        </KeyboardAvoidingView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
   // STYLES //
});

components/Index.js

import AsyncStorage from '@react-native-community/async-storage';

export function serializeKey(data) {
    var formBody = [];
    for (var property in data) {
      var encodedKey = encodeURIComponent(property);
      var encodedValue = encodeURIComponent(data[property]);
      formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");
    return formBody;
}

export async function isLogin() {
    var session = await AsyncStorage.getItem("session_ticket");
    if (session != null)
        return true;
    return false;
}

export async function setSessionTicket(ticket) {
    AsyncStorage.setItem("session_ticket", ticket);
}

components/Input.js

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

export default class Input extends Component {
  state = {
    text: '',
  };
  render() {
    return (
      <View>
        <TextInput
          {...this.props}
          placeholderTextColor="#ddd"
          style={styles.input}
          value={this.state.text}
          ref={this.props.inputRef}
          onChangeText={text => this.setState({text})}
        />
      </View>
    ); 
  } 
}

const styles = StyleSheet.create({
  // STYLES //
});

components/MyButton.js

import React, {Component} from 'react';
import {StyleSheet, Text, TouchableOpacity} from 'react-native';
import PropTypes from 'prop-types';

export default class MyButton extends Component {
  render() {
    return (
      <TouchableOpacity
        style={[styles.button, 
        {backgroundColor: this.props.bgColor}]}>
        <Text style={{color: this.props.textColor}}>{this.props.text}</Text>
      </TouchableOpacity>
    );
  }
}

MyButton.propTypes = {
  text: PropTypes.string.isRequired,
  bgColor: PropTypes.string,
  textColor: PropTypes.string,
};

const styles = StyleSheet.create({
  // STYLES //
});

package.json

{
  "name": "bookreen",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.7.1",
    "mobx": "^5.15.1",
    "mobx-react": "^6.1.4",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-gesture-handler": "^1.5.2",
    "react-native-reanimated": "^1.4.0",
    "react-native-router-flux": "^4.0.6",
    "react-native-screens": "^1.0.0-alpha.23",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "7.7.5",
    "@babel/plugin-proposal-decorators": "^7.7.4",
    "@babel/runtime": "7.7.6",
    "@react-native-community/eslint-config": "0.0.5",
    "babel-jest": "24.9.0",
    "eslint": "6.7.2",
    "jest": "24.9.0",
    "metro-react-native-babel-preset": "^0.56.3",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

App.js (Routes)

import React, { Component } from 'react';
import {
    AppRegistry
} from 'react-native';
import {Actions, Scene, Router} from 'react-native-router-flux';

import Anaekran from './ekranlar/Anaekran';
import MahalDetay from './ekranlar/MahalDetay';
import ToplantiList from './ekranlar/ToplantiList';
import Login from './ekranlar/Login';

export default class LoginApp extends Component {

    render() {
        const scenes = Actions.create(
          <Scene key="root" hideNavBar={true}>
        <Scene key="Login" component={Login}/>
            <Scene key="Anaekran" component={Anaekran}/>
            <Scene key="MahalDetay" component={MahalDetay}/>
            <Scene key="ToplantiList" component={ToplantiList}/>
          </Scene>
        );

        return <Router scenes={scenes}/>
    }
}

AppRegistry.registerComponent('App', () => App);

Solution

  • You are passing onPress property into MyButton component but you are not handling that property inside MyButton.js. That's why your Giris function is not being executed at all. You should handle that property inside MyButton and pass that prop to TouchableOpacity like(notice the line that starts with onPress):

    <TouchableOpacity
        style={[styles.button, 
        {backgroundColor: this.props.bgColor}]}
        onPress={this.props.onPress}>
        <Text style={{color: this.props.textColor}}>{this.props.text}</Text>
    </TouchableOpacity>