# Data and State

Tuesday, November 17

---

# 📆 Today

- [On their own](../../build/on-their-own.milestone.md) is due now
- Data and state: what your app remembers, and where
- Work time: [Make it real](../../build/make-it-real.milestone.md), due next Tuesday at 2:30
- **Thursday:** quiz (15 minutes, in the Quiz Space), then work time

---

<!-- id: this-week-in-ai -->

<x-sfx-cue src="../assets/this-week-in-ai-theme.mp3" on="player:block-enter" />

![@image(fit=contain).background](../assets/this-week-in-ai.png)

---

[@embed 6.2](https://x.com/OpenAI/status/2122750124543926515?a=ox6uZsLvLfFFcaH8DPY&s=20)

---

[@embed nov 17](https://x.com/SamVale29/status/2121483268763587009?a=ybfAe5WoyEjJMG5W-Js&s=20)

---

<!--
play:
  variant: section
-->

# Data and state

---

# Two words

| Word      | Means                         | In a daily word puzzle                 |
| --------- | ----------------------------- | -------------------------------------- |
| **State** | What your app stores right now | The letters you've typed, guesses left |
| **Data**  | What your app persists           | Your streak, yesterday's score         |

^ State turns into data when your app saves it somewhere. Reload the page: whatever was only state is gone.

---

# Client and server

- **The client** is the browser on your user's phone. It runs your page.
- **A server** is a computer that answers requests. It can keep data for everyone.
- Many good apps only have a client.

^ Every app in this class has a client. Some also have a server, and every app that uses the course AI or a public API talks to someone else's server.

---

# Where data lives

| Where                                        | Who sees it            | How long it lasts                | For example                       |
| -------------------------------------------- | ---------------------- | -------------------------------- | --------------------------------- |
| **The page** (memory)                        | This tab               | Until a reload                   | The timer on a practice session   |
| **This browser** (`localStorage`)            | This person, here      | Until they clear it              | A guitar player's practice log    |
| **Your server** (a database)                 | Whoever you allow      | Until you delete it              | A roommate chore board            |
| **Someone else's server** (an API, the AI)   | Whoever they allow     | Their choice                     | Tonight's pickup soccer standings |

^ Pick the place closest to the top that still works. Each step down adds work, and something else to keep safe.


---

# How data moves

- **A request and a response:** the page asks (`fetch`), a server answers. One trip.
- **JSON** is the shape the answer takes: names and values, like a filled-in form
- **A cookie** rides along with each request, so your server knows who's asking
- **Staying connected** (a WebSocket) only when people need to see each other _right now_

^ A recipe-from-a-photo app sends the photo and waits for the AI's JSON: one request, one response. A chore board can just check every few seconds, or when you open it. Live connections are for a shared whiteboard or a game against a friend, and few apps need them.

---


# Your nouns are your data

A roommate chore board:

| Noun          | What it keeps           |
| ------------- | ----------------------- |
| **Household** | name, invite code       |
| **Person**    | name, which household   |
| **Chore**     | what, how often         |
| **Done**      | which chore, who, when  |

^ In a database, each noun is a table and each one you save is a row. The "which household" and "who" columns are the links between tables. You've seen this already: the `schema` you give the course AI describes the same kind of shape.

---

# What to store vs compute

| Store                       | Compute      |
| -------------------------- | ------------------------ |
| Each day you played        | Your streak              |
| Each book you finished     | Pages read this month    |
| Each chore someone did     | Whose turn it is next    |

^ If you save the streak _and_ the days, they'll disagree someday. Keep one source of truth.

---

<!--
play:
  variant: section
-->

# Handling many users

---

# Each user has their own state and data

- **This browser** gives it for free: every phone has its own `localStorage`
- **On a server,** every row says whose it is, or which group it belongs to
- **Shared on purpose** is different: the chore board _should_ show everyone's chores

^ The bug to look for: one person's practice log, saved game or job list shows up for someone else, or overwrites it.

---

# Check it yourself

1. Open your app on your phone and in a **private window** on your laptop (e.g. command + shift + N)
2. Use it as two different people
3. **Reload** both. Is everything still there?
4. Does either one see, or change, the other's work? Should it?

^ A private window starts with an empty `localStorage`, so it acts like a stranger's phone. If your app has a server, check again after a deploy: only `DATA_DIR` survives one.

---

# Data storage

| Ask                                              | If yes                                   |
| ------------------------------------------------ | ---------------------------------------- |
| Does _someone else_ need to see it?                | A server                                 |
| Does it follow them to another device?           | Accounts                                 |
| Would it matter if someone faked it?             | The server decides, not the page         |
| None of these?                                   | `localStorage`, and you're done          |

^ A leaderboard needs a server, but often only a name typed once, not accounts. See [A server for your app](../../project/guides/bun.guide.md) and [Accounts in your app](../../project/guides/accounts.guide.md).

---

# NOT on the client (browser)

- **API keys:** the course adds them for you
- **Anything a cheater would change:** scores, prices, who won
- **Someone else's private data:** the page shows only what this person may see

^ Anyone can open the browser's tools and read or change what the page holds. That's fine for your own practice log, and not fine for a leaderboard.

---

<!--
play:
  variant: section
-->

# Your Data section

---

# Add a data section to your project.md

| What it remembers  | Where it lives | Who sees it      | How long it lasts |
| ------------------ | -------------- | ---------------- | ----------------- |
| Practice sessions  | This browser   | The player       | Until cleared     |
| Tonight's standings | A sports API  | Everyone         | Updated each game |

Then: **where your data comes from** (people, an API, the course AI), and **why that's enough** for your users.

^ Write it in your own words. If your app keeps nothing, say why it doesn't need to: that's an answer too.

---

# Ask your agent to walk you through it

```prompt
Read my app's code and docs/project.md. List everything my app remembers, and for each one tell me where it lives (the page, this browser, a server, or an API), who can see it, and how long it lasts. Then ask me whether that's what my users need. Don't write my Data section for me: add the heading and the table's columns, and I'll fill them in.
```

---

<!--
play:
  variant: section
-->

# Work time

"Make it real", due next Tuesday at 2:30

---

# Make it real

1. **Write** your Data section in `docs/project.md`
2. **Decide** if anything has to move: to the browser, a server, or accounts
3. **Build** the smallest version that works, if it needs one
4. **Check** two people and a reload: nothing lost, nothing crossed

^ If your app already keeps the right things in the right place, your Data section is how you show it.

---

# Thursday

- **2:30:** Quiz, 15 minutes, in the Quiz Space
- Then work time on [Make it real](../../build/make-it-real.milestone.md)

[A server for your app](../../project/guides/bun.guide.md) · [Accounts in your app](../../project/guides/accounts.guide.md) · [The Studio](../../project/index.md)
