CodeBlanks Logo Icon CodeBlanks

Auth and API

Write auth context and API integration.

Adding an auth context

In this lesson we will create an AuthContext and wrap App with its provider. We initialize with createContext(null); null is the default value, meaning no one is signed in. A useAuth hook reads the context.

The auth state holds user and setUser. On a successful login you call setUser(token); on logout setUser(null). The provider's value gives both. Before an API call you read the token with const { user } = useAuth() and add it to the Authorization header. This pattern is the foundation of medium and large apps.

Loading tasks with API fetch

Once the auth context is in place we call fetch inside useEffect. The URL is 'https://api.example.com/tasks'. We add the user token to the Authorization header. The returned JSON is written to state with setTasks.

Example: fetch(url, { headers: { Authorization: 'Bearer ' + user } }). The dependency array is [user]; this way the request re-fires when user changes. A .catch handles errors. This flow is the standard for data loading in real apps: auth first, then data.

Practice Add AuthContext and provider

Create an AuthContext with createContext(null). Write a useAuth hook with useContext. In App hold a user state with useState(null); wrap the return with <AuthContext.Provider value={{ user, setUser }}>.

Starter code

App.js
import React, { useState } from 'react';
import { Text, View } from 'react-native';

function App() {
  const [tasks, setTasks] = useState([]);
  return (
    <View>
      <Text>Field Report</Text>
    </View>
  );
}

// Add the login context and provider here

Sample solution

App.js
import React, { useState } from 'react';
import { Text, View } from 'react-native';

function App() {
  const [tasks, setTasks] = useState([]);
  return (
    <View>
      <Text>Field Report</Text>
    </View>
  );
}

const AuthContext = createContext(null);
export function useAuth() { return useContext(AuthContext); }

function App() {
  const [tasks, setTasks] = useState([]);
  const [user, setUser] = useState(null);
  return (
    <AuthContext.Provider value={{ user, setUser }}>
      <View>
        <Text>Field Report</Text>
      </View>
    </AuthContext.Provider>
  );
}

Questions and answers

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

1 createContext call

Question
const AuthContext = ____(null);
Answer
const AuthContext = createContext(null);

Explanation: createContext creates a new context.

2 What does the useAuth hook return?

App.js
const { user } = useAuth();
  • A state
  • A context
  • The context value Correct answer
  • An array

Explanation: useAuth returns the context value.

3 Match each piece to its role

Term Meaning
AuthContext Context definition
Provider Supplies the value
useAuth Reads the value
user Token carrying state

All lessons in Advanced