Learn Nuxt Β· 5/12

State Management: Keeping Track of Data

8 min read

State Management: Keeping Track of Data πŸ’Ύ

Hey there, code adventurer! Welcome to the fascinating world of state management in Nuxt. Ever felt like your application's data has a mind of its own, popping up in one place but mysteriously vanishing in another? You're not alone. Let's get that data wrangled!

What is State and Why Does it Need Managing?

In the context of a web application, state is simply any piece of data that can change over time. Think of a user's login status, the items in a shopping cart, or whether a dark mode theme is active.

The Problem: Imagine you're building an e-commerce site. A user adds an item to their cart on the product page. Then, they navigate to the homepage. How does the little shopping cart icon in the header know to update the item count? What if they go to a completely different category page? The cart count needs to be consistent everywhere.

This is where state management comes in. It's the practice of making sure your application's data is consistent, predictable, and accessible across different components and pages. Without it, our app would be like a forgetful friend, constantly asking, "Wait, who are you again?" every time you move to a new page.


1. Global State with useState 🌍

Nuxt provides a handy built-in composable called useState to handle simple global state. Think of it as creating a special, memorable piece of information that your entire application can access.

useState is built on top of Vue's reactivity system, which means that whenever the value of a useState variable changes, any part of your application using it will automatically update. Magic! ✨

How it solves the problem: Instead of each component having its own local copy of data (like the number of items in a cart), we can create a single, global source of truth with useState. Any component can then read from or write to this central piece of information.

Under the Hood: When you use useState, Nuxt creates a globally shared reactive reference. This reference is keyed, meaning you give it a unique name to access it from anywhere in your app. During server-side rendering, this state is stored and then "hydrated" (transferred) to the client-side, ensuring consistency.

Let's see it in action:

Imagine we want to keep track of a counter that can be updated from different components.

composables/useCounter.ts (It's a good practice to organize your state in the composables directory)

typescript
export const useCounter = () => useState<number>('counter', () => 0)
  • 'counter' is the unique key for our state.
  • () => 0 is a function that sets the initial value of our state to 0.

Now, any component can use this counter.

components/TheCounter.vue

vue
<template>
  <div>
    <p>Current count: {{ counter }}</p>
  </div>
</template>

<script setup>
const counter = useCounter();
</script>

components/CounterControls.vue

vue
<template>
  <div>
    <button @click="counter++">Increment</button>
    <button @click="counter--">Decrement</button>
  </div>
</template>

<script setup>
const counter = useCounter();
</script>

Now, you can place <TheCounter /> and <CounterControls /> anywhere in your application, and they will both be perfectly in sync with the same counter value!


2. Sharing State Across Components and Pages 🀝

As you saw in the example above, sharing state with useState is incredibly straightforward. The key is that as long as you use the same unique key ('counter' in our case), Nuxt ensures you get the exact same reactive state variable.

This is perfect for things like:

  • User authentication status (Is the user logged in?)
  • Theme settings (Dark or light mode?)
  • Shopping cart contents

A more practical scenario: User Authentication

Let's create a simple state to track if a user is logged in.

composables/useAuth.ts

typescript
interface User {
  name: string;
  email: string;
}

export const useUser = () => useState<User | null>('user', () => null)

Now, on our login page, we can update this state.

pages/login.vue

vue
<template>
  <button @click="login">Log In</button>
</template>

<script setup>
const user = useUser();

function login() {
  // In a real app, you'd fetch this from an API
  user.value = { name: 'Jane Doe', email: '[email protected]' };
  navigateTo('/profile');
}
</script>

And in our site header, we can display a welcome message.

components/TheHeader.vue

vue
<template>
  <header>
    <nav>
      <!-- navigation links -->
    </nav>
    <div>
      <p v-if="user">Welcome, {{ user.name }}!</p>
      <p v-else>Please log in.</p>
    </div>
  </header>
</template>

<script setup>
const user = useUser();
</script>

No matter which page the user navigates to, the header will always show the correct login status because it's reading from our global useUser state.


3. Integrating Pinia for Robust Store Management 🍍

useState is fantastic for simple, global state. But what happens when your application grows? You might have multiple related pieces of state, and actions that modify that state in specific ways (like fetching user data, adding an item to a cart, and calculating the total).

This is where a dedicated state management library like Pinia comes in. Pinia is now the officially recommended state management solution for Vue and Nuxt.

The Problem Pinia Solves: As your app gets more complex, you might find yourself with many useState composables. It can become difficult to track how and where your state is being changed. Pinia provides a more structured way to organize your state, actions (methods that change the state), and getters (computed properties of your state).

Think of Pinia as creating "stores" for different features of your application (a user store, a cart store, a products store). It's like having dedicated, highly organized departments for your application's data.

Getting Started with Pinia in Nuxt

First, you'll need to install Pinia and the official Nuxt module for it.

bash
npm install pinia @pinia/nuxt

Then, add the module to your nuxt.config.ts:

typescript
export default defineNuxtConfig({
  modules: [
    '@pinia/nuxt',
  ],
})

That's it for the setup! Nuxt takes care of the rest.

Creating a Pinia Store

Let's recreate our counter example using Pinia.

stores/counter.ts

typescript
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    },
  },
})
  • state is where you define your data.
  • getters are like computed properties for your store.
  • actions are methods that can modify the state.

Using the Pinia Store in a Component

components/PiniaCounter.vue

vue
<template>
  <div>
    <p>Current count: {{ counterStore.count }}</p>
    <p>Double count: {{ counterStore.doubleCount }}</p>
    <button @click="counterStore.increment()">Increment</button>
    <button @click="counterStore.decrement()">Decrement</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '~/stores/counter';
const counterStore = useCounterStore();
</script>

As you can see, this is a much more organized approach. All the logic related to the counter is neatly contained within its own store.

Fun Fact: Pinia is the Spanish word for pineapple! 🍍 The creator chose the name because pineapples are often a symbol of hospitality and are a group of individual flowers that join together to create a single fruit, much like how Pinia stores come together to form your application's state.


4. Persisting State Across Page Reloads πŸ”„

There's one little "gotcha" with both useState and Pinia by default. If you refresh the page, your state will reset to its initial value. This is because the state is stored in your computer's memory, which is cleared on a page reload.

The Problem: Imagine your user has carefully selected 10 items for their shopping cart. They accidentally hit the refresh button, and... poof! The cart is empty. That's a surefire way to lose a customer.

The Solution: We need to store the state somewhere that persists between page loads. The most common place for this is the browser's localStorage.

Luckily, there are easy ways to achieve this without writing a lot of manual code to save and retrieve from localStorage.

Persisting State with a Plugin

For Pinia, the community has created a handy plugin: pinia-plugin-persistedstate.

Installation:

bash
npm install pinia-plugin-persistedstate

Next, we need to create a Nuxt plugin to tell Pinia to use our new persistence plugin.

plugins/persistedState.ts

typescript
import { defineNuxtPlugin } from '#app'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

export default defineNuxtPlugin(nuxtApp => {
  const pinia = createPinia()
  pinia.use(piniaPluginPersistedstate)
  nuxtApp.vueApp.use(pinia)
});

(Self-correction based on newer Nuxt/Pinia practices): A simpler and more modern way to add the plugin in Nuxt is to directly extend the Pinia instance.

A better way with Nuxt 3:

plugins/persistedState.client.ts (Note the .client.ts extension so it only runs on the client-side, as localStorage is not available on the server).

typescript
import { defineNuxtPlugin } from '#app';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.$pinia.use(piniaPluginPersistedstate);
});

Now, you can simply enable persistence on a per-store basis.

stores/counter.ts

typescript
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  // ... getters and actions
  persist: true, // This is the magic line!
})

With persist: true, the state of this store will be automatically saved to localStorage whenever it changes and rehydrated when the page is reloaded. It's that simple!


Further Reading & References

Challenge

Challenge

You are building the state management layer for a new e-commerce application in Nuxt. Your task is to implement two key features: a global theme switcher and a persistent shopping cart.

Requirements:

  1. Theme Management with useState: Create a Nuxt composable file named useTheme.ts. Inside this file, define and export a function that utilizes useState to manage the application's theme. The state should be uniquely identified with the key 'theme' and have an initial value of 'light'.

  2. Shopping Cart with Pinia: Define a Pinia store for the shopping cart in a file named cart.ts. The store must have the ID 'cart' and include the following:

    • A state property named items, initialized as an empty array. Each item in the array will be an object with at least an id property.
    • A getter named totalItems that returns the total count of items in the cart.
    • An action named addItem that accepts a new item object and adds it to the items array.
    • An action named removeItem that accepts an itemId and removes the item with the matching id from the items array.
  3. State Persistence: Modify the Pinia cart store definition to ensure its state is automatically saved to localStorage and rehydrated on page reloads.

Expected result

Your submission should consist of two complete code blocks representing the two files.

  1. composables/useTheme.ts:

    • This file must export a default function useTheme.
    • Inside the function, useState must be called with the key 'theme' and a default value of 'light'.
  2. stores/cart.ts:

    • This file must import defineStore from pinia.
    • It must export a store created with defineStore('cart', ...).
    • The store definition must include a state function returning an object with an items array.
    • It must include a getters object with a totalItems getter that calculates the length of the items array.
    • It must include an actions object with addItem and removeItem methods that correctly manipulate the items state.
    • The store options object must include the property persist: true at the top level to enable persistence.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.