1

I have a field for email and password, when I click on login button I am calling a method to fetch user from backend, and if the response is success I should be able to navigate to next page. How do I do that? I have an api which is working fine in Postman, how do I connect api with UI and store the response data? here below I have attached a response image of an api which I am using in code

enter image description here

  import React from 'react';
    import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
    import PresentationalComponent from './PresentationalComponent'

    export default class App extends React.Component {
       constructor(){
           super();
           this.state = {
            email: '',
            password: '',
            result: false,
           }
       }

       updateState = () => {
          this.setState({ myState: 'The state is updated' })
       }

       _userLogin() {
         var email = this.state.username;
         var password = this.state.password;
         if (email && password) { // if validation fails, value will be null
           fetch("http://localhost:5000/api/login", {
             method: "POST",
             headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
             },
             body: JSON.stringify({
               username: email,
               password: password,
             })
           })
           .then((response) => response.json())
           .then((responseData) => {
             console.log(responseData);
             AlertIOS.alert(
               "Login Success!",
               "Click the button to get a Chuck Norris quote!"
             ),
             this._onValueChange(STORAGE_KEY, responseData.id_token)
           })
           .done();
           renderResults();
         }
       }

       renderResults = () => {
           if(responseData){
                this.setState({
                    result: true
                })
           }
       }

       handleEmail = (text) => {
             this.setState({ email: text })
       }

       handlePassword = (text) => {
             this.setState({ password: text })
       }

       render() {
          return (
             <View>
                {this.state.result ?
                     <PresentationalComponent/>
                     :
                     <View>
                        <TextInput
                          underlineColorAndroid = "transparent"
                          placeholder = "Email"
                          placeholderTextColor = "#9a73ef"
                          autoCapitalize = "none"
                          onChangeText = {this.handleEmail}
                        />
                        <TextInput
                           underlineColorAndroid = "transparent"
                           placeholder = "Password"
                           placeholderTextColor = "#9a73ef"
                           autoCapitalize = "none"
                           onChangeText = {this.handlePassword}
                        />
                        <Button
                             onPress={this._userLogin}
                             title="Learn More"
                             color="#841584"
                             accessibilityLabel="Learn more about this purple button"
                         />
                     </View>
                }
             </View>
          );
       }
    }

2 Answers 2

1

If you use react-navigation it's quite simple

if (response.status == "200") 
{
this.props.navigation.navigate(" ") //Add the page name in quote 
}
Sign up to request clarification or add additional context in comments.

Comments

0

I found this article which you might find helpful.

It recommends using two tokens - looking at your current API response, I don't see any tokens - it is important to understand that tokens and IDs are two different concepts - you might want to generate tokens in your login procedure. These are strings that let the server make sure that a client is authenticated.

Suggested implementation, from to the article (slightly simplified):

  1. When the user logs in, the server generates a refresh token, and includes it in the response, so that the app can save it
  2. The client can use the refresh token to obtain an access token (also generated by the server, but expires after an hour for security reasons)
  3. The client sends its access token with every request to a protected route in the header, in Authorization
  4. The server validates the access token before processing the request

When the user opens the app, say, a day later, it should continue from step 2 to get a new access token.

When the user logs out, the app should make a request to revoke both tokens so they cannot be used anymore.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.