CodeBlanks Logo Icon CodeBlanks

Login

Learn the login screen and flow.

The login screen

The login screen asks the user for email and password. You use two TextInput components: one for email, one for password. The password field should set secureTextEntry to true; this hides the characters. Each input is kept in component state (useState).

On submit you call setLoading(true); when the request ends you call setLoading(false). A loading indicator appears on the button. On success you call login(data) to update the auth context; the user is navigated to the main screen.

The handleSubmit flow

When the user presses submit, handleSubmit is called. First setLoading(true), then a fetch request goes to the server. If the response is successful you call login({ user, token }) to update the auth context. On error you inform the user with Alert.alert.

The function must be async and awaited. Writing setLoading(false) in a finally block ensures the indicator clears even on error. This pattern repeats in every login flow.

Practice Call the login function

Complete the onSubmit function. Call login({ user: 'ayse', token: 'abc' }). Get login from the auth context with useContext(AuthContext).

Starter code

App.js
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';

export function useLogin() {
  // get auth from the context

  async function onSubmit() {
    // call login
  }

  return { onSubmit };
}

Sample solution

App.js
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';

export function useLogin() {
  const auth = useContext(AuthContext);

  async function onSubmit() {
    auth.login({ user: 'ayse', token: 'abc' });
  }

  return { onSubmit };
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Hide the password field

Question
<TextInput
  value={password}
  onChangeText={setPassword}
  ____={true}
/>
Answer
<TextInput
  value={password}
  onChangeText={setPassword}
  secureTextEntry={true}
/>

Explanation: secureTextEntry hides the password.

2 Why must handleSubmit be async?

  • Because animations run async Correct answer
  • Because styles load async
  • Because fetch is awaited
  • Because TextInput requires async

Explanation: fetch is awaited; that is why it must be async.

3 Match the login parts

Term Meaning
TextInput Reads user input
secureTextEntry Hides the password
setLoading Manages the loading state
Alert.alert Reports an error

All lessons in Advanced