React Native
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.
Exercise 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 }}>.
Show example solution
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>
);
}
Test yourself
-
createContext call
const AuthContext = ____(null);
Show answer
const AuthContext = createContext(null);
-
What does the useAuth hook return?
const { user } = useAuth();
- A state
- A context
- The context value
- An array
Show answer
The context value — useAuth returns the context value.
-
Match each piece to its role
- AuthContext
- Context definition
- Provider
- Supplies the value
- useAuth
- Reads the value
- user
- Token carrying state
Next lesson: Native features