# Part 2: Vue reactivity and browser-local state

In Part 1, we got Vue and FastAPI running together. Before we start building our backend, let's think about what our voting application should actually do.

We need somewhere to write a question, enter the possible answers and create a poll. We should be able to select an answer, submit a vote and see the results. None of these interactions requires a server if we are the only person using the application.

For now, we will leave FastAPI as it is and see how far we can get using Vue alone.

As in Part 1, run commands from the `voting-app` directory. Keep `uv run scripts/devserver.py` running and <http://localhost:3100> open in your browser. Vite will update the page as we edit the frontend files.

## 1. Making the interface react to data

Our generated application displays a greeting. Let's turn this into a simple poll editor, starting with the question.

In `frontend/src/components/HelloWorld.vue`, add an input below the existing `<h1>`:

```vue
<p><label>Question <input /></label></p>
```

Type a question into the input. The browser happily displays what we type, but what if we also want to display the question as a heading? The text currently belongs to the input element. We have not given Vue a value that both the input and the heading can use.

With ordinary JavaScript, we could listen for input events, read the input's value and manually update the heading. We would have to repeat this whenever another part of the interface needed the same information.

Vue takes a different approach. We describe how the interface depends on our data, and Vue updates the relevant elements whenever that data changes. This is called *reactivity*.

### Giving our question a state

We need a place to keep the question that Vue can observe. We could keep it inside the component, but later we want to display our polls elsewhere in the application. Pinia gives us a convenient place to keep reactive data that several Vue components need to access. Our generated project already has a small Pinia counter store, which we can reuse as a starting point.

Rename it:

```sh
mv frontend/src/stores/counter.js frontend/src/stores/polls.js
```

Replace the contents of `frontend/src/stores/polls.js` with:

```js
import { defineStore } from 'pinia'

export const usePollsStore = defineStore('polls', {
  state: () => ({
    question: '',
  }),
})
```

`defineStore` defines a named store that our components can access by calling `usePollsStore()`. The `state` function describes the initial data in the store. Pinia makes its properties reactive and directly accessible to our components. We use this form of `defineStore`, called an Options Store, throughout the tutorial.

The health check in our greeting component has served its purpose in Part 1. Replace the contents of its `<script setup>` block with the following, removing the generated props, `backendStatus`, the `onMounted` hook and their imports:

```js
import { usePollsStore } from '../stores/polls'

const polls = usePollsStore()
```

Now connect the input and heading to the same value. Replace the existing heading and our temporary input with:

```vue
<h1 class="green">{{ polls.question || 'Pollroom' }}</h1>
<p><label>Question <input v-model="polls.question" /></label></p>
```

Replace the generated Vite, Vue and FastAPI status content inside `<h3>` with `Your poll`. In `App.vue`, remove the `msg` attribute from `<HelloWorld />`, since we no longer use that prop.

Try typing the question again. This time the heading changes with every keystroke. Clear the input and the heading returns to `Pollroom`.

The `{{ ... }}` expression displays the current question, with a fallback for the empty string. `v-model` connects the input to the same state in both directions: typing changes the value in the store, and changing the value in the store changes the input.

We did not have to tell Vue which elements to update. Nor did we have to send anything to FastAPI.

### Making room for the polls

Our greeting has become a poll editor, so let's give the component a more appropriate name:

```sh
mv frontend/src/components/HelloWorld.vue frontend/src/components/PollForm.vue
```

In `frontend/src/App.vue`, update the corresponding import:

```js
import PollForm from './components/PollForm.vue'
```

And replace `<HelloWorld />` with:

```vue
<PollForm />
```

We will use the other side of the generated layout to display the polls we create. Replace `<TheWelcome />` in `<main>` with a temporary placeholder:

```vue
<p>No polls yet.</p>
```

Remove the `TheWelcome` import from `<script setup>`. We can also remove the unused generated components:

```sh
rm -r frontend/src/components/TheWelcome.vue frontend/src/components/WelcomeItem.vue frontend/src/components/icons
```

<picture>
  <source srcset="/_f/d5b6349b215f" media="(prefers-color-scheme: dark)">
  <img src="/_f/6466aa455481" alt="Typing a question updates the heading in the browser-only poll editor">
</picture>

## 2. Building a poll draft

Try writing a question such as "Where should we meet?". We can display the question, but we cannot yet give anyone a choice of answers.

We could add a separate state property for every answer, but we don't know how many options a particular poll will need. An array is a better representation of a list of possible answers. Let's start it with two empty strings.

In `frontend/src/stores/polls.js`, extend the `state` object:

```js
state: () => ({
  question: '',
  options: ['', ''],
}),
```

How do we display one input for every entry in the array? Vue provides `v-for`, which repeats an element for each item in a collection. It can also give us the item's index, so we can bind an input to the corresponding array element.

In `PollForm.vue`, add the following after the question paragraph:

```vue
<p v-for="(option, index) in polls.options" :key="index">
  <label>Option {{ index + 1 }} <input v-model="polls.options[index]" /></label>
</p>
<ul>
  <li v-for="(option, index) in polls.options" :key="index">
    {{ option || `Option ${index + 1}` }}
  </li>
</ul>
```

We are using the same array twice: once to generate the inputs and again to preview the answers. The `:key` helps Vue identify each rendered item when updating the list. The index is sufficient here because we only append options; we do not remove or reorder them.

Type two answers. Both the inputs and the preview reflect the same data, just as our question input and heading did earlier.

The input fields may look uneven because the labels have different widths. We can align them with a small CSS grid. Add these rules to the existing `<style scoped>` block in `PollForm.vue`:

```css
.greetings label {
  display: grid;
  grid-template-columns: 5rem 1fr;
  align-items: center;
  gap: 0.5rem;
}

.greetings input {
  width: 100%;
}
```

### Adding another option

Suppose our meeting poll needs a third answer. We already have everything we need to display it: if the array contains three elements, both `v-for` loops will render three rows.

We only need a way for the user to append an empty string to the array.

Pinia lets us define operations on our state as *actions*. Add an `actions` section after `state` in the store definition. Our complete store now looks like this:

```js
import { defineStore } from 'pinia'

export const usePollsStore = defineStore('polls', {
  state: () => ({
    question: '',
    options: ['', ''],
  }),
  actions: {
    addOption() {
      this.options.push('')
    },
  },
})
```

Inside an action, `this` refers to the store itself. We can access its properties directly, just as a component accesses them through `polls`.

In `PollForm.vue`, add a button between the option inputs and the preview list:

```vue
<button type="button" @click="polls.addOption()">Add option</button>
```

The `@click` directive calls our function when the button is clicked. The action changes the array in the store, rather than manipulating the interface directly.

Click the button a few times. Each click adds another input and another preview item. We did not need to create any HTML elements ourselves; Vue reacts to changes in the array, including changes to its length.

<picture>
  <source srcset="/_f/f399c226f9dd" media="(prefers-color-scheme: dark)">
  <img src="/_f/dbe84f54c361" alt="Question and a variable number of options update their local preview">
</picture>

## 3. Creating a poll

So far, we have been editing a single question and a list of answers. Try writing a second poll. As soon as we replace the question in the editor, the first one is gone.

There is an important distinction between the draft we are currently writing and a poll we have finished creating. The draft can be changed freely, while a completed poll should remain available even after we clear the editor.

Let's keep completed polls in a separate array. Initially it is empty:

Add this property to `state`, beside `question` and `options`:

```js
polls: [],
```

### Knowing when the draft is ready

Before we create a poll, we need a non-empty question and at least two non-empty answers. We could store a Boolean indicating whether the form is valid and update it after every keystroke. But this value would only duplicate information that we already have in our reactive state. It would be easy to forget to update it when something changes.

Pinia provides *getters* for values derived from the state. Add a `getters` section alongside `state` and `actions`:

```js
getters: {
  canCreate: state =>
    Boolean(state.question.trim()) &&
    state.options.filter(option => option.trim()).length >= 2,
},
```

The getter is recalculated when the state it depends on changes. From the component or an action, we read `canCreate` like any other store property, without calling it as a function. We can use the same condition both to disable a button and to prevent the creation action from running with incomplete data.

### From draft to completed poll

What should a completed poll contain? For now, just a question, a list of answers and an identifier. Two different polls might have the same question, so the question itself would not make a reliable identifier.

Add a creation action beside `addOption` inside `actions`:

```js
createPoll() {
  if (!this.canCreate) return

  const poll = {
    id: crypto.randomUUID(),
    question: this.question.trim(),
    options: this.options.map(option => option.trim()).filter(Boolean),
  }
  this.polls.push(poll)
  this.question = ''
  this.options = ['', '']
},
```

We create a new object with a unique ID and a new array containing the non-empty answers. We can then clear the original draft without affecting the completed poll.

In `PollForm.vue`, wrap the question input, option inputs and Add option button in a form. Open the form immediately before the question paragraph:

```vue
<form @submit.prevent="polls.createPoll()">
```

After the Add option button, insert the submit button and close the form. Keep the heading, preview list and `<h3>` outside it:

```vue
<button :disabled="!polls.canCreate">Create poll</button>
</form>
```

Normally, submitting an HTML form causes the browser to navigate or reload. We want to run our JavaScript action instead, so we use `@submit.prevent` to prevent the default behavior. The `:disabled` binding makes the button reflect our getter. Submitting with the keyboard works through the same form event.

Fill in a question and one answer. The Create poll button should remain disabled. Fill in a second answer and the button becomes available. Submit the form: our editor clears.

Where did the poll go? We stored it in Pinia, but have not yet displayed our collection anywhere.

### Sharing state between components

Our editor lives in `PollForm.vue`, while the main area for displaying polls belongs to `App.vue`. We could pass the data from one component to the other, but both can access the same Pinia store directly.

In the `<script setup>` block of `frontend/src/App.vue`, import the store and obtain an instance:

```js
import { usePollsStore } from './stores/polls'

const polls = usePollsStore()
```

This is the same store instance that `PollForm.vue` uses within the application, not a new copy of its data.

Replace our temporary "No polls yet" placeholder with the following:

```vue
<p v-if="polls.polls.length === 0">No polls yet.</p>
<article v-for="poll in polls.polls" :key="poll.id">
  <h2>{{ poll.question }}</h2>
  <ul>
    <li v-for="(option, index) in poll.options" :key="index">{{ option }}</li>
  </ul>
</article>
```

`v-if` displays an element only when its condition is true. We use it for the empty collection, while `v-for` renders an article for every completed poll. Here the poll's ID is a better key than its position in the array, because it identifies the poll independently of its order.

Create two or three polls. The editor clears after each submission, while the completed polls stay visible in the main area. Notice that `PollForm` never has to tell `App` to refresh its display. The two components are simply reading and changing the same reactive data.

<picture>
  <source srcset="/_f/cafeab958ffa" media="(prefers-color-scheme: dark)">
  <img src="/_f/068ffcabd47a" alt="A created poll remains visible after the local editor resets">
</picture>

## 4. Casting a vote

We can create and display polls, but at the moment their answers are just strings. Where would we record how many votes each answer has received?

Rather than maintaining a separate list of vote counts that must stay in step with our answers, let's make each option an object containing both its label and its count.

In `createPoll`, replace the `options` property of the new poll with:

```js
options: this.options
  .filter(option => option.trim())
  .map(label => ({ label: label.trim(), votes: 0 })),
```

We still use strings while the user is composing a poll. Only the completed poll needs vote counts.

The previous display expects strings, so temporarily change `{{ option }}` to `{{ option.label }}` in the list of completed poll options in `App.vue`. Reload the page so we start with an empty store, then create a poll and check that its options are displayed as before.

### Selecting is not voting

A radio button lets us choose one answer from a group. But what should happen when the user changes their mind before submitting? If selecting an answer immediately incremented its vote count, simply clicking back and forth between two answers could produce several votes.

Just as we distinguished an unfinished poll from a completed poll, we need to distinguish an unfinished selection from a submitted vote.

Add these properties to `state`:

```js
voteDrafts: {},
votedPollIds: [],
```

We use an object keyed by poll ID for the current selections: each poll can have its own selected option. The second value is a list of the polls for which this page has already submitted a vote.

In `createPoll`, immediately after `this.polls.push(poll)`, initialize the selection for the new poll:

```js
this.voteDrafts[poll.id] = null
```

`null` means we haven't selected an answer yet. Once the user selects one, we will store its array index.

Add a `submitVote` action that uses the selection to find and increment the corresponding option:

```js
submitVote(poll) {
  if (this.votedPollIds.includes(poll.id)) return

  const option = poll.options[this.voteDrafts[poll.id]]
  if (!option) return

  option.votes += 1
  this.votedPollIds.push(poll.id)
},
```

This is the point at which the count changes. Our action also records the poll ID so we do not let the same page submit another vote on it.

### Showing the voting form and results

We need two views of a poll: one in which we can select an answer, and one in which we can see the results after voting. We can use the submitted-vote record to decide which view is displayed.

In `App.vue`, replace the option list inside each poll's `<article>` with:

```vue
<form v-if="!polls.votedPollIds.includes(poll.id)" @submit.prevent="polls.submitVote(poll)">
  <p v-for="(option, index) in poll.options" :key="index">
    <label>
      <input v-model="polls.voteDrafts[poll.id]" type="radio" :name="`poll-${poll.id}`" :value="index" />
      {{ option.label }}
    </label>
  </p>
  <button :disabled="polls.voteDrafts[poll.id] === null">Submit vote</button>
</form>
<div v-else>
  <h3>Results</h3>
  <ul>
    <li v-for="(option, index) in poll.options" :key="index">
      {{ option.label }}: {{ option.votes }} {{ option.votes === 1 ? 'vote' : 'votes' }}
    </li>
  </ul>
</div>
```

All radio buttons belonging to a poll share a name and bind to the same selection. Each has a different numeric `:value`, representing its option's index. The submit button stays disabled until we have made a selection.

Create a poll and try selecting different answers without submitting. If you have two polls, check that their radio buttons work independently. Now submit a vote: the voting form disappears and the results appear, with exactly one vote recorded.

The `v-else` is the counterpart of our `v-if`. When the poll ID is added to `votedPollIds`, Vue switches to the results view. For now, the rule against repeated voting only applies to this running application; we will come back to that limitation later.

<picture>
  <source srcset="/_f/72e4b164a348" media="(prefers-color-scheme: dark)">
  <img src="/_f/03f3d463d337" alt="Results appear only after a local vote is submitted">
</picture>

## 5. Editing a poll

Create a poll and imagine noticing a spelling mistake in the question. It would be useful to correct it without creating a new poll or losing its votes.

We already know how to edit reactive data with `v-model`. We could bind a new input directly to `poll.question`, but then the poll would change with every keystroke. What would a Cancel button do? The original wording would already have been overwritten.

We solved a similar problem when creating polls: the unfinished input belongs in a draft. Let's use the same idea for editing an existing poll.

### Keeping a separate copy

We only need to edit one poll at a time. Add this property to `state`:

```js
editing: null,
```

When it is `null`, we are not editing anything. When we start editing, it will contain the ID of the poll and a copy of the values we want to edit. Add two actions:

```js
startEdit(poll) {
  this.editing = {
    pollId: poll.id,
    question: poll.question,
    options: poll.options.map(option => ({ ...option })),
  }
},

cancelEdit() {
  this.editing = null
},
```

Strings can simply be copied. Objects are different: assigning `poll.options` to the draft would share the original array, and copying only the array would still share the option objects inside it. Using `map` and the object spread syntax (`...option`) creates a new object for each option.

This makes cancellation simple. We only have to discard the draft; there is nothing to undo in the original poll.

### Applying the changes

When the user saves, we find the poll using the ID stored in the draft and apply the new wording. For simplicity, we will allow changes to the question and existing option labels, but not adding, removing or reordering options in this editor. This way a vote remains associated with the same option.

Add the save action:

```js
saveEdit() {
  if (!this.editing) return

  const poll = this.polls.find(poll => poll.id === this.editing.pollId)
  if (
    !poll ||
    !this.editing.question.trim() ||
    this.editing.options.some(option => !option.label.trim())
  ) {
    return
  }

  poll.question = this.editing.question.trim()
  poll.options.forEach((option, index) => {
    option.label = this.editing.options[index].label.trim()
  })
  this.editing = null
},
```

We update only the question and labels, not the vote counts. The draft represents the changes the user intends to make, rather than a replacement for the entire poll.

### Switching between editing and viewing

The poll should display the editing form when its ID matches the one in our editing draft. Otherwise, it should display its question and voting or results view as before.

In `App.vue`, insert this form inside the poll's `<article>`, immediately before its `<h2>`:

```vue
<form v-if="polls.editing?.pollId === poll.id" class="edit-form" @submit.prevent="polls.saveEdit()">
  <p><label>Edit question <input v-model="polls.editing.question" required /></label></p>
  <p v-for="(option, index) in polls.editing.options" :key="index">
    <label>Edit option {{ index + 1 }} <input v-model="option.label" required /></label>
  </p>
  <button>Save changes</button>
  <button type="button" @click="polls.cancelEdit()">Cancel</button>
</form>
```

Wrap the existing question and voting/results markup in a `<template v-else>...</template>` immediately after the editing form. Vue can conditionally render several elements together using a `<template>`, without adding another element to the resulting HTML.

Inside that template, add a button after the poll question:

```vue
<button type="button" @click="polls.startEdit(poll)">Edit</button>
```

As in the creation form, we can align the inputs. Add these rules to the existing `<style scoped>` block in `App.vue`:

```css
.edit-form label {
  display: grid;
  grid-template-columns: 7rem 1fr;
  align-items: center;
  gap: 0.5rem;
}

.edit-form input {
  width: 100%;
}
```

The `.edit-form` selector confines these layout rules to the editor, leaving the radio-button labels alone.

Create a poll, submit a vote and open it for editing. Change both the question and an option label, then press Cancel. The original wording should be unchanged. Try again, this time saving the edit. The new wording should appear, and the vote count should remain intact.

<picture>
  <source srcset="/_f/c30af12ef962" media="(prefers-color-scheme: dark)">
  <img src="/_f/1fcd34db2513" alt="An independent draft edits a question and option labels without losing votes">
</picture>

## Where does our data live?

We now have a usable voting interface. Vue takes care of keeping the display in sync with the application state, and Pinia allows our components to work with the same data. We also learned to distinguish drafts, which belong to the user's current interaction, from completed polls and votes.

Try one more experiment. Open the application in a second browser tab, keeping the first one open. Create a poll in the first tab and switch to the second. Where is the new poll?

Although our two Vue components use the same store, the two tabs are running separate JavaScript applications. Each has its own instance of Pinia. Even within the same browser, changes to one store do not affect the other.

Now reload the first tab. Our polls and votes disappear, because the page's JavaScript state is recreated from its initial values.

![Poll form and results share Pinia within each browser, but separate browsers have independent stores](/_f/df4b0798ad11)

We could preserve the polls by writing them to the browser's local storage, but that would not help someone using another device participate in the same vote. We need a common place to keep the poll data, while letting each user maintain their own unfinished forms and selections.

In [Part 3](/coders/fullstack/fastapi), we will bring FastAPI back into the picture and explore how the browser and server can work together.

{cards: coders/fullstack/fastapi}
