Saving is off. The course database is down: labs work for practice, but nothing is saved.The course database is down.

LAB05

REST & GraphQL, Async JS, and Auth — Build a Real Attendance App

Learn REST and GraphQL (every HTTP verb, query params), sync vs async JavaScript, and Clerk vs BetterAuth — then build a small Expo app that checks you into the real class attendance system. Before the Expo app, 13 checked exercises in the browser take you step by step from JSON to a real check-in.

Intermediate 6 h 15 minrest-apisgraphqlhttp-methodsasync-javascriptauthenticationfetchaxios

Your progress

0 / 13 exercises

10 parts · 6 h 15 min

Before you start

Who’s doing Lab 05?

This lab is open any time. Enter your name and student ID to start. Your work is saved.

By the end you will

  • Explain every HTTP verb (GET, POST, PUT, PATCH, DELETE) and when to use each
  • Read and write a query string (?key=value) and know what it's for
  • Compare REST and GraphQL and choose the right one for a given use case
  • Explain the difference between synchronous and asynchronous code, and when each fits
  • Compare Clerk and BetterAuth and choose the right one for a given app
  • Call a real backend from an Expo app with fetch, or with Axios if you prefer it — POST, GET, and an external API
  • Read JSON, send GET and POST requests, and show loading and error states, step by step in 13 checked exercises — the last one checks you in for real

You need

  • Lab 04 completed: Expo Router, feature-first folders, global state
  • A new, empty folder for this lab — this is a standalone project
  • Node.js, VS Code and Git installed (Setup)
  • Expo Go on your phone, or the Android emulator

Part 1: REST APIs — HTTP verbs & query params

45 min

A REST API is a set of URLs (“resources”) you talk to with plain HTTP. The verb says what kind of thing you’re doing to that resource; the URL says which resource.

read

GET

Read a resource. Never changes anything on the server — safe to call as often as you like.

create

POST

Create a new resource, or run an action that is not a simple update (like "check in").

replace

PUT

Replace a resource with a full, new version. Send every field, even the ones that did not change.

update

PATCH

Update part of a resource — just the fields that changed. (Not used much in this lab, but you should recognise it.)

remove

DELETE

Remove a resource.

Query parameters

A query string is the part of a URL after ? — key=value pairs, joined with &. It never changes which resource you’re asking for, only how much of it, or which part.

GET/todos?done=true&limit=5
  1. GETread, never changes anything
  2. /todosthe resource
  3. ?done=truea filter
  4. &limit=5a page size

Common uses: filtering (?done=true), search (?q=shoes), and pagination (?page=2&limit=20). The server reads them off request.url — nothing about the verb or the body changes.

fetch vs Axios

fetch is built into JavaScript — no install, but you handle JSON parsing and error status yourself. Axios is a small library (npm install axios) that does both automatically and reads a little shorter. They do the exact same job; this lab lets you pick either one.

fetch

  • Built in — nothing to install
  • One fewer dependency to update
  • You call JSON.stringify() and res.json() yourself
  • fetch does not reject on a 404/500 — you must check res.ok

Axios

  • res.data is already parsed JSON
  • Rejects automatically on a bad status — one catch handles it
  • axios.create({ baseURL }) avoids repeating the full URL
  • One more package in node_modules
Live demo

A real REST API, running on this page

api.ts (fetch)
// plain fetch — built in, no install
const BASE = 'https://api.example.com/todos';

const getTodos   = (q = '') => fetch(`${BASE}${q}`).then(r => r.json());
const addTodo    = (title) => fetch(BASE, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title }),
}).then(r => r.json());
const toggleTodo = (id, done) => fetch(`${BASE}/${id}`, {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ done }),
}).then(r => r.json());
const deleteTodo = (id) => fetch(`${BASE}/${id}`, { method: 'DELETE' });

Request / response log

      Tapping the box sends a real PUT, the + sends a real POST, the ✕ a real DELETE, and each filter chip a real GET with a query string — watch the log. Flip the fetch / Axios switch above: same four calls, written two ways.

      Checkpoint

      In the demo above: tick a todo (that’s a real PUT), add one (a real POST), delete one (a real DELETE), then tap “Done” — that’s a real GET with ?done=true in the query string. Read the log after each tap.

      Part 2: GraphQL vs REST

      20 min

      GraphQL is a different way to ask a server for data: one URL (usually /graphql), and the client says exactly which fields it wants in a query (read) or a mutation (write).

      REST

      • Simple: a URL + a verb, works with plain fetch()
      • Easy to cache (the URL is the cache key)
      • Over/under-fetching: you get whatever shape the endpoint returns

      GraphQL

      • Ask for exactly the fields you need, nothing more
      • One request can gather data that would be several REST calls
      • More setup: a schema, resolvers, a GraphQL client

      Rule of thumb: a small app with a handful of simple resources (this lab’s attendance app included) → REST. A large app with many related, nested resources and picky mobile data usage → GraphQL starts paying for itself.

      Live demo

      The same data, asked for in GraphQL

      query.graphql
      query GetTodos {
        todos {
          id
          title
          done
        }
      }

        One endpoint, /graphql, answers both — you ask for exactly the fields you want. REST instead gives you whatever shape /todos returns.

        Part 3: Synchronous vs asynchronous code

        30 min

        Synchronous code runs one line at a time; each line waits for the one before it to finish. Asynchronous code lets a slow operation (a network call, a file read, a timer) run in the background while the rest of your program keeps going.

        Use sync for

        Fast, in-memory work: math, string formatting, array transforms — anything that finishes in microseconds.

        Use async for

        Anything that waits on something outside the CPU: fetch(), reading a file, a timer, a database query.

        On a phone, the UI thread is the same thread your JavaScript runs on. A synchronous call that takes 3 seconds freezes the whole screen for 3 seconds — no scrolling, no taps. An async call frees the thread while it waits, so the UI stays alive.

        Sync vs async

        Read file
        Call API
        Resize image
        UI thread — keeps beating only if it's free

        Checkpoint

        Run both modes above. In “Synchronous” the UI-thread dot freezes solid until all three bars finish. In “Asynchronous” it keeps beating the entire time — that beat is your app staying responsive.

        Part 4: Authentication — Clerk vs BetterAuth

        35 min

        Both are ways to add sign-up, sign-in and sessions to an app without writing that logic yourself.

        Clerk

        A fully hosted auth service. You install their SDK and drop in prebuilt UI; Clerk runs the servers, the database and the dashboard.

        BetterAuth

        An open-source auth library you self-host. You own the database and the server; BetterAuth gives you the logic, not the infrastructure.

        // npm install @clerk/clerk-expo
        import { ClerkProvider } from '@clerk/clerk-expo';
        
        export default function RootLayout() {
          return (
            <ClerkProvider publishableKey={process.env.EXPO_PUBLIC_CLERK_KEY}>
              {/* your app */}
            </ClerkProvider>
          );
        }
        // npm install better-auth
        import { betterAuth } from 'better-auth';
        
        export const auth = betterAuth({
          database: { provider: 'postgres', url: process.env.DATABASE_URL },
          emailAndPassword: { enabled: true },
        });
        ClerkBetterAuth
        HostingClerk’s serversYour own server/database
        CostFree tier, then per monthly active userFree (you pay only for your own hosting)
        Setup speedMinutes — prebuilt UI componentsLonger — you build the UI yourself
        ControlLimited to what Clerk exposesFull control over data and logic
        Best forShipping fast, small teams, don’t want to run serversFull control, data residency rules, cost at large scale

        Pick Clerk when speed to launch matters more than owning the stack — most student projects and early-stage startups. Pick BetterAuth when you must self-host (cost at scale, data residency, or you already run your own backend).

        Live demo — sign-in flow

        Sign-in call
        Session created
        useUser() / useSession()
        Protected screen

        sign-in call

        reading the session

        Part 5: Data your app can read: objects and JSON

        35 min

        Parts 5 to 8 build the attendance check-in step by step: first the data a server sends, then a request, then waiting for the answer, then sending data. Every exercise runs here in the browser, in the phone preview, and is checked automatically. Your progress is saved. The last exercise (13) checks you in for real.

        Objects: values with names

        An object groups values under names. Each name is a key, and each key has a value. You read a value with a dot: object.key.

        const student = { name: 'Mona Adel', year: 2, present: true };
        
        student.name;     // 'Mona Adel'  ← the value stored under the key "name"
        student.year;     // 2
        student.present;  // true
        student.age;      // undefined   ← this key does not exist

        Arrays: lists of values

        An array is a list in square brackets. Each item has a position, called its index. Counting starts at 0.

        const courses = ['Mobile', 'Web', 'AI'];
        
        courses[0];      // 'Mobile'  ← index 0 is the first item
        courses[2];      // 'AI'
        courses.length;  // 3         ← how many items

        An array can hold objects. This is the shape of almost every list an API sends: a class list, a list of products, a list of messages.

        const students = [
          { id: 1, name: 'Mona Adel', present: true },
          { id: 2, name: 'Omar Khaled', present: false },
        ];
        
        students[1].name;  // 'Omar Khaled'
        students.length;   // 2

        JSON: an object written as text

        A server cannot send a JavaScript object over the internet. It sends text. JSON (JavaScript Object Notation) is the format of that text. It looks like an object, with stricter rules:

        Keys in double quotes

        {"name": "Mona"}, never {name: "Mona"}.

        Strings in double quotes

        "Mona", never 'Mona'. Single quotes make the text invalid.

        No comments, no extra commas

        JSON is only data: nothing after the last item, no // notes.

        Two functions move between the two forms:

        • JSON.stringify(object) turns an object into JSON text. Your app uses it to send data.
        • JSON.parse(text) turns JSON text into an object. Your app uses it to read data it received.

        One student, two forms

        Choose a kind of value: it lights up in both forms.

        Every value in JSON is one of six kinds. Choose one above.

        In your code: a JavaScript object

        const student = {
          name: 'Mona Adel',
          year: 2,
          present: true,
          courses: ['Mobile', 'Web'],
          address: { city: 'Cairo' },
        };
        

        On the network: JSON text (one string)

        {"name":"Mona Adel","year":2,"present":true,"courses":["Mobile","Web"],"address":{"city":"Cairo"}}
        // press a button to run it
        const student = { name: 'Mona Adel', present: true };
        
        const text = JSON.stringify(student);  // '{"name":"Mona Adel","present":true}'  ← a string
        text.name;                             // undefined: a string has no keys
        
        const again = JSON.parse(text);        // an object again
        again.name;                            // 'Mona Adel'

        Try it in a live example. Change the code: the phone updates as you type.

        ● LIVE DEMOJSON text → object → screenLoading the editor and preview…

        Now three small exercises, then a bigger one.

        EX 01Name every part of a JSON objectLoading the exercise…
        EX 02What will the code print?Loading the exercise…
        EX 03Turn JSON text into an objectLoading the exercise…

        Many objects on the screen: FlatList

        To show an array of objects, React Native uses FlatList (you met it in Lab 02). It needs three props:

        <FlatList
          data={students}                                       // the array to show
          keyExtractor={(s) => String(s.id)}                    // a unique text for each row
          renderItem={({ item }) => <Text>{item.name}</Text>}  // draws ONE row; item is one student
        />

        renderItem runs once for every item in data. Whatever it returns is one row on the screen.

        EX 04Show a class list from JSONLoading the exercise…

        Checkpoint

        You can now read an object (student.name), an array (students[0]) and JSON text (JSON.parse(text)), and draw a list. Next: get that JSON from a real server.

        Part 6: What is an API? Requests and responses

        40 min

        What an API is

        Your app does not keep the class list itself. The list lives on a server: a computer on the internet that keeps data and runs code. Your app asks the server for data, or sends data to it.

        An API (Application Programming Interface) is the list of addresses (URLs) a server offers, and the rules for each one: what to send, and what comes back.

        Client

        Your app. It sends requests and shows the answers.

        Server

        A computer on the internet. It keeps the data and sends responses.

        API

        The URLs the server offers and the rules for each one.

        One API call, step by step

        Press Next to follow one request from the phone to the server and back. The code line that runs at each step lights up.

        One API call

        Step 1 / 5

        Class listLoading…
        the app (client)
        the server
        async function loadAll() {
          const res = await fetch(`${API}/students`);
          const data = await res.json();
          setStudents(data);
        }
        

        The parts of a request

        A request has a method, a URL, and sometimes headers and a body.

        GEThttps://labverse-indol.vercel.app/api/lab5/students?present=true
        1. GETthe method: read data and change nothing
        2. https://labverse-indol.vercel.appthe server
        3. /api/lab5/studentsthe path: which data
        4. ?present=truethe query string: a filter (Part 1)
        • Method: what kind of action. GET reads, POST sends (Part 1 has all of them).
        • URL: the full address: the server, then the path, then an optional query string.
        • Headers: extra information about the request, for example “the body is JSON”.
        • Body: the data you send. A GET has no body. A POST usually has one.

        This lab has a practice API on the course server. It never stores anything, so call it as often as you like:

        GET

        /api/lab5/students

        All 5 students, as a JSON array.

        GET

        /api/lab5/students?present=true

        Only the present students. ?present=false gives the absent ones.

        GET

        /api/lab5/students/2

        One student by id. An id that does not exist gives 404.

        POST

        /api/lab5/echo

        Send any JSON: the server answers with exactly what it received.

        The full address starts with https://labverse-indol.vercel.app, for example https://labverse-indol.vercel.app/api/lab5/students. Open it in a new browser tab: you see the JSON the server sends.

        The parts of a response

        The server always answers with a status code (a three-digit number that says how the request went) and usually a body (the data, as JSON text).

        2xx — success

        • 200 OK: here is what you asked for
        • 201 Created: something new was saved

        4xx — fix your request

        • 400 Bad request: the data is wrong
        • 404 Not found: nothing at this URL

        5xx — the server has a problem

        • 500 Server error: the server broke
        • 503 Unavailable: closed for now
        EX 05Put one API call in orderLoading the exercise…
        EX 06What does each status code mean?Loading the exercise…

        fetch: your first request in code

        fetch is built into JavaScript. It sends a request and gives you the response. Read this code line by line:

        async function loadAll() {
          const res = await fetch('https://labverse-indol.vercel.app/api/lab5/students'); // 1
          const data = await res.json();                                                // 2
          setStudents(data);                                                            // 3
        }
        1. fetch(url) sends a GET request to the URL. await waits until the response arrives. res is the response: res.status is the status code, res.ok is true for 200–299.
        2. res.json() reads the body and turns the JSON text into an array. Reading takes time too, so it also needs await. (It does the JSON.parse step of Part 5 for you.)
        3. setStudents(data) saves the array in state. React draws the screen again, now with the list.

        To load the data once when the screen opens, call the function inside useEffect with an empty list [] (Lab 02):

        useEffect(() => {
          loadAll();
        }, []);
        ● LIVE DEMOA real GET request, line by lineLoading the editor and preview…
        EX 07Your first GET: load the class listLoading the exercise…

        Checkpoint

        Your app now talks to a real server: method + URL out, status code + JSON back. Next: what happens while it waits, and when something goes wrong.

        Part 7: Waiting for the answer: await and errors

        35 min

        async and await

        A request takes time: often 0.1 to 2 seconds, sometimes more on slow Wi-Fi. fetch does not give you the response at once. It gives you a promise: a value that arrives later.

        • await waits for a promise and gives you its value.
        • You can write await only inside a function marked async.
        • While one function waits, the rest of the app keeps working: buttons and scrolling still respond (you saw this in Part 3).
        const res = fetch(url);         // no await: res is a promise, not the response yet
        const res = await fetch(url);   // await: res is the response

        Two kinds of failure

        A request can fail in two different ways, and your code must handle both:

        The server answered with an error

        • A wrong URL (404), bad data (400), a server problem (500)
        • fetch does not throw: check res.ok yourself

        There was no answer at all

        • No internet, or a wrong server name
        • fetch throws an error: catch it with try / catch
        async function load() {
          try {
            const res = await fetch(url);
            if (!res.ok) {                  // the server answered with an error (404, 500, …)
              setMessage(`Error ${res.status}`);
              return;                       // stop: do not read the body
            }
            const data = await res.json();  // only for a good answer
            setMessage(`Hello, ${data.name}`);
          } catch {                         // no answer at all
            setMessage('No connection. Try again.');
          }
        }

        The states of a screen that waits

        A screen that waits for a server is always in one of a few states. Keep the state in useState and draw something different for each one:

        Four states of one screen

        Lab 05 attendanceAttendance is OPENCould not check. Try again.Choose what the network does ↑

        state = 'idle'

        async function check() {
          setState('loading');
          try {
            const res = await fetch(`${API}/attendance/status`);
            if (!res.ok) {
              setState('error');      // the server answered with an error
              return;
            }
            const data = await res.json();
            setState(data.open ? 'open' : 'closed');
          } catch {
            setState('error');        // no answer at all
          }
        }
        

        Each button replays the same code with a different answer from the network.

        EX 08What does await do?Loading the exercise…
        EX 09Catch the errorLoading the exercise…

        The real attendance API: is it open?

        The course server has a real attendance API. This address tells you whether check-in is open:

        GEThttps://labverse-indol.vercel.app/api/attendance/status
        1. GETread only
        2. https://labverse-indol.vercel.appthe course server
        3. /api/attendance/statusthe attendance status
        { "open": true, "database": "connected", "password": true }

        You only need open: true means students can check in now. The next exercise puts everything from this part together: loading, the answer, and errors.

        EX 10Is attendance open?Loading the exercise…

        Checkpoint

        You can now wait for an answer, show a spinner while waiting, and show a clear message for both kinds of failure. Next: send data.

        Part 8: Sending data: POST and the real check-in

        45 min

        GET reads, POST sends

        To send data, the request needs three things that a GET does not have:

        const res = await fetch('https://labverse-indol.vercel.app/api/lab5/echo', {
          method: 'POST',                                  // 1. send data
          headers: { 'Content-Type': 'application/json' }, // 2. the body is JSON
          body: JSON.stringify({ name: 'Mona' }),          // 3. the body, as JSON text
        });
        const data = await res.json();                     // the server's answer
        1. method: 'POST': this request sends data. Without it, fetch makes a GET, and a GET cannot carry a body.
        2. headers: extra information. 'Content-Type': 'application/json' tells the server how to read the body.
        3. body: the data. It must be text, so JSON.stringify turns the object into JSON text.

        Build a request below and send it to the echo server. Turn off one piece at a time and read what goes wrong:

        Build a POST request

        Change the pieces. Watch the code and the request change. Then send it for real.

        The pieces

        Your code

        What travels over the network

        The server's answer

        Press “Send”.
        ● LIVE DEMOA POST request and the server’s answerLoading the editor and preview…
        EX 11Send your first POSTLoading the exercise…

        The attendance API: check in

        This is the real API your TA uses for attendance:

        POSThttps://labverse-indol.vercel.app/api/attendance
        1. POSTsend data
        2. https://labverse-indol.vercel.appthe course server
        3. /api/attendancecheck in
        { "name": "Mona Adel", "studentId": "240001", "deviceId": "lab05-k3j2h1g4f5d6s7a8" }
        • name: your full name, letters only.
        • studentId: your student ID, digits only.
        • deviceId: any text of 16–64 letters, digits, dots or dashes that names your device. The starter code makes one for you.

        It answers in one of these ways:

        201 — checked in

        { "ok": true, "entry": { "name", "studentId", "at" } }. at is the time of your check-in.

        200 — already checked in

        { "ok": true, "already": true, … }. Your first check-in is kept.

        400 — wrong data

        { "error": "invalid", "errors": { "name": "…" } } says which field is wrong.

        503 — closed

        { "error": "closed" }. Check-in is not open right now.

        EX 12Read the server's answerLoading the exercise…

        Put it all together: the check-in screen

        The last exercise is the core of this lab. Your screen will:

        1. Check that the name and the ID are not empty. If one is empty, show a red message and send nothing.
        2. Set the state to 'sending' and show a spinner.
        3. Send the POST with { name, studentId, deviceId }.
        4. Read the answer and show it: checked in, already checked in, wrong data, or an error.
        5. Catch a lost connection.

        When you press Check, the checker types the name and ID you gave in Start lab and presses your Check in button. That request is real: your attendance for Lab 05 is saved, and your TA sees it.

        EX 13Check in with the APILoading the exercise…

        CheckpointParts 5–8 complete

        When Exercise 13 shows Solved, you are checked in for Lab 05. In Parts 9 and 10 you build the same check-in as a real Expo app: in the Code Editor (Option A, in the lab) or on your own computer (Option B).

        Part 9: Project setup

        15 min

        There are two ways to set up the attendance app. In the lab, use Option A.

        Option A · In the Code Editor (in the lab)

        The Code Editor on this site has the project ready for you: the folders, the two starter screens, shared/device.ts and the two api.ts files of Part 10. Nothing to install. The app runs in a phone emulator next to your code and updates as you type. A Guide panel on the left lists every step, and a click on a file name opens that file.

        Lab 05 attendance app in the Code EditorReact Native · phone emulator · nothing to install · a Guide panel with every step
        • The project is saved in this browser. The same button opens it again. You also find it in the Code editor’s start screen, under Lab projects.
        • fetch and Axios both work there. You do not install anything.
        • Skip the commands below and go straight to Part 10.

        Option B · On your own computer

        Same Expo setup as Lab 04 — you already know this part.

        Terminal — create
        npx create-expo-app@latest attendance-app
        cd attendance-app
        npm run reset-project
        Terminal — Axios (optional)
        only run this if you want to use Axios instead of fetch — either is fine for every exercise
        npm install axios
        Terminal — NativeWind
        npx expo install nativewind tailwindcss react-native-reanimated react-native-safe-area-context
        then follow the NativeWind install guide for your installed version (tailwind.config.js, global.css, babel/metro)
        module.exports = {
          content: ['./app/**/*.{js,jsx,ts,tsx}', './features/**/*.{js,jsx,ts,tsx}'],
          presets: [require('nativewind/preset')],
          theme: { extend: {} },
          plugins: [],
        };
        attendance-app
        • app/
        • _layout.tsx
        • (tabs)/
        • _layout.tsx
        • index.tsxCheck in -> CheckInScreen
        • lookup.tsxExternal API -> PokemonScreen
        • features/
        • attendance/
        • api.ts * STUB
        • screens/
        • CheckInScreen.tsx * STUB
        • external/
        • api.ts * STUB
        • screens/
        • PokemonScreen.tsx * STUB
        • shared/
        • device.tsgenerates and stores the deviceId once

        Quick folders + starter files (Git Bash / macOS / Linux):

        Terminal
        mkdir -p features/attendance/screens features/external/screens shared
        touch features/attendance/api.ts features/attendance/screens/CheckInScreen.tsx features/external/api.ts features/external/screens/PokemonScreen.tsx shared/device.ts

        On Windows PowerShell:

        "features/attendance/screens","features/external/screens","shared" | ForEach-Object { New-Item -ItemType Directory -Force $_ }
        "features/attendance/api.ts","features/attendance/screens/CheckInScreen.tsx","features/external/api.ts","features/external/screens/PokemonScreen.tsx","shared/device.ts" | ForEach-Object { New-Item -ItemType File -Force $_ }

        Starter UI — paste before you touch the REST API

        The exercises in Part 10 are about fetch/Axios, not layout. Paste these two screens into app/(tabs)/index.tsx and app/(tabs)/lookup.tsx now, run the app once to see them render, then come back and fill in the TODOs inside submit() / search() as you work through Part 10.

        import { useState } from 'react';
        import { View, Text, TextInput, Pressable, ActivityIndicator } from 'react-native';
        
        type Status = { kind: 'idle' } | { kind: 'loading' } | { kind: 'success'; message: string } | { kind: 'error'; message: string };
        
        export default function CheckInScreen() {
          const [name, setName] = useState('');
          const [studentId, setStudentId] = useState('');
          const [status, setStatus] = useState<Status>({ kind: 'idle' });
        
          const submit = async () => {
            setStatus({ kind: 'loading' });
            // TODO (Exercise 10.1): call checkIn(name, studentId) from '@/features/attendance/api'
            // and turn the result into setStatus({ kind: 'success', message } | { kind: 'error', message }).
          };
        
          const disabled = !name.trim() || !studentId.trim() || status.kind === 'loading';
        
          return (
            <View className="flex-1 bg-slate-50 px-6 pt-20">
              <View className="mb-8">
                <Text className="text-xs font-bold tracking-widest text-emerald-600">ATTENDANCE</Text>
                <Text className="mt-1.5 text-3xl font-bold text-slate-900">Check in</Text>
                <Text className="mt-2 text-base leading-snug text-slate-500">Type your name and student ID, then submit.</Text>
              </View>
        
              <View className="gap-4">
                <View className="gap-2">
                  <Text className="text-sm font-semibold text-slate-700">Full name</Text>
                  <TextInput
                    className="h-14 rounded-2xl border border-slate-200 bg-white px-4 text-base text-slate-900"
                    value={name}
                    onChangeText={setName}
                    placeholder="Mariam Ahmed"
                    placeholderTextColor="#94a3b8"
                    autoCapitalize="words"
                  />
                </View>
        
                <View className="gap-2">
                  <Text className="text-sm font-semibold text-slate-700">Student ID</Text>
                  <TextInput
                    className="h-14 rounded-2xl border border-slate-200 bg-white px-4 text-base text-slate-900"
                    value={studentId}
                    onChangeText={setStudentId}
                    placeholder="236541"
                    placeholderTextColor="#94a3b8"
                    keyboardType="number-pad"
                  />
                </View>
        
                <Pressable
                  className={`mt-1.5 h-14 items-center justify-center rounded-2xl ${disabled ? 'bg-emerald-300' : 'bg-emerald-600 active:scale-[0.98] active:opacity-90'}`}
                  onPress={submit}
                  disabled={disabled}
                >
                  {status.kind === 'loading' ? <ActivityIndicator color="#ffffff" /> : <Text className="text-base font-bold text-white">Submit</Text>}
                </Pressable>
        
                {status.kind === 'success' && (
                  <View className="rounded-2xl bg-emerald-100 p-3.5"><Text className="text-sm font-semibold text-slate-900">{status.message}</Text></View>
                )}
                {status.kind === 'error' && (
                  <View className="rounded-2xl bg-red-100 p-3.5"><Text className="text-sm font-semibold text-slate-900">{status.message}</Text></View>
                )}
              </View>
            </View>
          );
        }
        import { useState } from 'react';
        import { View, Text, TextInput, Pressable, ActivityIndicator, Image } from 'react-native';
        
        type Pokemon = { name: string; sprite: string; types: string[] };
        type Status = { kind: 'idle' } | { kind: 'loading' } | { kind: 'success'; data: Pokemon } | { kind: 'error'; message: string };
        
        export default function PokemonScreen() {
          const [query, setQuery] = useState('');
          const [status, setStatus] = useState<Status>({ kind: 'idle' });
        
          const search = async () => {
            if (!query.trim()) return;
            setStatus({ kind: 'loading' });
            // TODO (Exercise 10.3): call getPokemon(query) from '@/features/external/api'
            // and turn the result into setStatus({ kind: 'success', data } | { kind: 'error', message }).
          };
        
          return (
            <View className="flex-1 bg-slate-50 px-6 pt-20">
              <View className="mb-7">
                <Text className="text-xs font-bold tracking-widest text-emerald-600">EXTERNAL API</Text>
                <Text className="mt-1.5 text-3xl font-bold text-slate-900">Pokémon lookup</Text>
                <Text className="mt-2 text-base text-slate-500">Type a name, e.g. pikachu.</Text>
              </View>
        
              <View className="flex-row gap-2.5">
                <TextInput
                  className="h-14 flex-1 rounded-2xl border border-slate-200 bg-white px-4 text-base text-slate-900"
                  value={query}
                  onChangeText={setQuery}
                  placeholder="pikachu"
                  placeholderTextColor="#94a3b8"
                  autoCapitalize="none"
                  autoCorrect={false}
                  onSubmitEditing={search}
                />
                <Pressable className="h-14 items-center justify-center rounded-2xl bg-emerald-600 px-6 active:scale-[0.98] active:opacity-90" onPress={search}>
                  <Text className="text-[15px] font-bold text-white">Search</Text>
                </Pressable>
              </View>
        
              <View className="mt-8 items-center">
                {status.kind === 'idle' && <Text className="text-sm text-slate-400">Results show up here.</Text>}
                {status.kind === 'loading' && <ActivityIndicator color="#059669" />}
                {status.kind === 'error' && <Text className="text-sm font-semibold text-red-600">{status.message}</Text>}
                {status.kind === 'success' && (
                  <View className="w-full items-center rounded-2xl border border-slate-200 bg-white p-6">
                    <Image source={{ uri: status.data.sprite }} className="h-32 w-32" />
                    <Text className="mt-2 text-xl font-bold capitalize text-slate-900">{status.data.name}</Text>
                    <View className="mt-3 flex-row gap-2">
                      {status.data.types.map((t) => (
                        <View key={t} className="rounded-full bg-emerald-100 px-3 py-1.5">
                          <Text className="text-xs font-bold capitalize text-emerald-700">{t}</Text>
                        </View>
                      ))}
                    </View>
                  </View>
                )}
              </View>
            </View>
          );
        }

        Both screens already handle loading, empty and error states — only the network call itself (the TODO) is left for Part 10.

        Part 10: Exercises — a real attendance app

        1 hour 15 min

        REST only

        This project trains REST, not GraphQL — every call below is a plain request to a real URL, nothing more.

        A real backend

        You POST and GET against the actual course attendance API — the same one the course uses for attendance.

        Your choice

        fetch or Axios — pick whichever you installed in Part 9 and use it everywhere below. Both are graded the same.

        Lab 05 attendance app in the Code EditorWorking in the Code Editor? Open your project here.

        The real address. The course site is labverse-indol.vercel.app, so BASE is https://labverse-indol.vercel.app/api/attendance. In the Code Editor project it is already filled in.

        The real answers. POST /api/attendance answers 201 { ok: true, entry } for a new check-in, 200 { ok: true, already: true, entry } when you were checked in before (for example in Exercise 13), 400 when the name or the student ID is wrong, and 503 when attendance is closed. Handle the 200 too, or a second check-in shows an error.

        These three exercises talk to the real course attendance API — the same one your TA uses to open check-in for this lab. There is nothing to fake here: a correct Exercise 10.1 really checks you in.

        Each solution below is hidden behind three hints — try it yourself first, open a hint if you’re stuck, and only press Show solution once you’ve genuinely tried.

        TASK 10.1

        POST — check in for real

        30 min

        shared/device.ts — every device needs one stable ID, generated once and reused:

        let cached: string | null = null;
        export function getDeviceId() {
          if (!cached) cached = crypto.randomUUID(); // 36 chars — well within the 16–64 range the API requires
          return cached;
        }

        features/attendance/api.ts — write a checkIn(name, studentId) function that POSTs { name, studentId, deviceId } to https://<your-course-site-domain>/api/attendance, using fetch or Axios (your choice from Part 9). studentId must be 5–9 digits (letters get rejected). It should return something your screen can switch on: a clear success case, an “already checked in” case, and a “closed” case.

        Build CheckInScreen with a name field, a student ID field, and a submit button that calls checkIn() and shows the result.

        Paste this into features/attendance/api.ts to start from, then fill in the TODOs:

        import { getDeviceId } from '@/shared/device';
        
        const BASE = 'https://<your-course-site-domain>/api/attendance';
        
        export async function checkIn(name: string, studentId: string) {
          // TODO: POST { name, studentId, deviceId: getDeviceId() } to BASE as JSON
          // TODO: 201 -> { ok: true, entry }
          // TODO: 200 with data.already -> { ok: true, entry, already: true }
          // TODO: 409 -> { ok: false, reason: 'device' | 'id' }
          // TODO: 503 -> { ok: false, reason: 'closed' }
          // TODO: anything else -> { ok: false, reason: 'error' }
        }
          TASK 10.2

          GET — is attendance open?

          15 min

          GET /api/attendance/status tells you whether attendance is open — it does not tell you whether you personally are checked in (the API never reveals names, on purpose). Write an attendanceOpen() function, call it when CheckInScreen mounts (useEffect), and show “Attendance is not open yet” instead of the form when it’s false. Whether you succeeded is answered by Exercise 10.1’s own response (201 vs 409), not by this endpoint.

          Paste this into features/attendance/api.ts to start from:

          export async function attendanceOpen() {
            // TODO: GET `${BASE}/status`
            // TODO: return the `open` field off the parsed JSON, as a boolean
          }
            TASK 10.3

            External API — look up a Pokémon

            30 min

            A REST API you don’t control at all: PokeAPI, no key required. Write getPokemon(name), then build PokemonScreen: a text input, a search button, and — on success — the sprite image, the name, and its types. On a bad name, show an error message instead of crashing.

            Paste this into features/external/api.ts to start from:

            export async function getPokemon(name: string) {
              // TODO: GET https://pokeapi.co/api/v2/pokemon/<name, trimmed + lowercased>
              // TODO: not found -> throw a friendly Error
              // TODO: return { name, sprite, types } pulled from the response
            }
              TASK 10.4

              Review your work

              10 min

              This lab is practice, not a hand-in — there’s nothing to submit. Before you move on, check it against the live demos earlier in this part:

              • You can explain every HTTP verb and name one real use for each
              • You can explain what a query string is for
              • You know one reason to pick REST and one reason to pick GraphQL
              • You can explain why a synchronous call freezes the UI and an async one doesn’t
              • You can explain one reason to pick Clerk and one reason to pick BetterAuth
              • You can explain one real difference between a fetch call and its Axios equivalent
              • Exercise 10.1 really checks you into attendance
              • Exercise 10.2 correctly hides the form when attendance is closed
              • Exercise 10.3 shows a real Pokémon’s sprite, name and types — and handles a typo without crashing

              CheckpointLab 05 complete

              🌐 You can now explain and use REST, GraphQL, async JavaScript and two real auth options — and you built an app that talks to the real course attendance system.

              Stuck?

              "Attendance is not open yet" from the real check-in
              Cause

              The attendance server is not set up or not reachable right now.

              Fix

              Check with your TA, or poll GET /api/attendance/status and only show the check-in button when open is true.

              409 "This student ID is already checked in"
              Cause

              You (or a classmate using your ID) already checked in.

              Fix

              This is correct behaviour, not a bug — a student ID can only check in once.

              400 "deviceId" error
              Cause

              The deviceId you sent is missing, or shorter than 16 characters.

              Fix

              Generate one with crypto.randomUUID() and send it as-is — do not shorten or edit it.

              The PokeAPI request returns a 404
              Cause

              The Pokémon name was misspelled, or had a capital letter.

              Fix

              PokeAPI names are lowercase, e.g. pikachu not Pikachu. Trim and lowercase whatever the student typed before building the URL.

              fetch() "Network request failed" on a phone
              Cause

              The real attendance API is an HTTPS endpoint, so this is almost always Wi-Fi, not localhost — but if you point this at your own machine later, remember localhost means the phone itself.

              Fix

              Use your computer's LAN IP, or test on the emulator first.

              Still stuck? Search the troubleshooting center or ask your TA.

              Optional

              Extra challenge

              Add a small retry with exponential backoff around the attendance POST (useful on flaky classroom Wi-Fi) — or build a tiny client-side cache so the PokeAPI screen does not re-fetch a Pokémon you already looked up this session.

              Resources

              End of lab · attendance

              Check in for Lab 05

              Checking whether check-in is open…