new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Nuxt · Getting started · all subjects

state

18 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

useState composable overview

useState is an SSR-friendly ref replacement that creates reactive and shared state across components. Its value is preserved after server-side rendering during client-side hydration and is shared across all components using a unique key.

useState serialization constraint

Data inside useState will be serialized to JSON, so it must not contain anything that cannot be serialized, such as classes, functions, or symbols.

useState best practice: never use ref() outside setup

Never define 'const state = ref()' outside of <script setup> or setup() function. For example, doing 'export myState = ref({})' would result in state shared across requests on the server and can lead to memory leaks.

useState best practice: use composable wrapper

Instead of directly exporting a ref, use the pattern 'const useX = () => useState("x")' to properly manage state.

useState basic usage example

Example showing basic useState usage: ```vue <script setup lang="ts"> const counter = useState('counter', () => Math.round(Math.random() * 1000)) </script> <template> <div> Counter: {{ counter }} <button @click="counter++"> + </button> <button @click="counter--"> - </button> </div> </template> ``` Any other component that uses useState('counter') shares the same reactive state.

Initialize state asynchronously with callOnce

To initialize state with asynchronously resolving data, use the callOnce util in the app.vue component. Example: ```vue <script setup lang="ts"> const websiteConfig = useState('config') await callOnce(async () => { websiteConfig.value = await $fetch('https://my-cms.com/api/website-config') }) </script> ``` This is similar to the nuxtServerInit action in Nuxt 2, allowing the initial state to be filled server-side before rendering the page.

clearNuxtState utility for cache invalidation

Use the clearNuxtState util to globally invalidate cached state.

Pinia module installation

To use Pinia with Nuxt, install the Pinia module with 'npx nuxt module add pinia' or follow the module's installation steps at https://pinia.vuejs.org/ssr/nuxt.html#Installation.

Pinia store with useState example

Example showing Pinia store usage with callOnce: Store file (app/stores/website.ts): ```ts export const useWebsiteStore = defineStore('websiteStore', { state: () => ({ name: '', description: '', }), actions: { async fetch () { const infos = await $fetch('https://api.nuxt.com/modules/pinia') this.name = infos.name this.description = infos.description }, }, }) ``` Usage in app.vue: ```vue <script setup lang="ts"> const website = useWebsiteStore() await callOnce(website.fetch) </script> <template> <main> <h1>{{ website.name }}</h1> <p>{{ website.description }}</p> </main> </template> ```

Shared state with auto-imported composables

Define global type-safe states using auto-imported composables from the composables directory and import them across the app. Example: File (composables/states.ts): ```ts export const useColor = () => useState<string>('color', () => 'pink') ``` Usage in app.vue: ```vue <script setup lang="ts"> const color = useColor() // Same as useState('color') </script> <template> <p>Current color: {{ color }}</p> </template> ```

Third-party state management libraries for Nuxt

Nuxt supports integration with multiple state management libraries: - Pinia (the official Vue recommendation) - Harlem (immutable global state management) - XState (state machine approach with tools for visualizing and testing state logic)

Nuxt 2 Vuex migration

Nuxt 2 used to rely on the Vuex library for global state management. If migrating from Nuxt 2, consult the migration guide. Nuxt is not opinionated about state management.

Vuex removed, use pinia instead

Nuxt 3 no longer provides Vuex integration. The official Vue recommendation is to use pinia, which has built-in Nuxt support via the @pinia/nuxt module.

Pinia installation and setup example

To use pinia for state management: Install pinia and @pinia/nuxt with 'yarn add pinia @pinia/nuxt'. Enable the module in nuxt.config.ts by adding '@pinia/nuxt' to modules. Create a store/index.ts file defining stores with defineStore from pinia. Create app/plugins/pinia.ts to globalize the store using defineNuxtPlugin.

Migrate to Vuex 4 if keeping Vuex

If you want to keep using Vuex instead of migrating to pinia, you can manually migrate to Vuex 4 following the official Vuex migration steps. Once done, add a plugin at app/plugins/vuex.ts that uses nuxtApp.vueApp.use(store) to register the store.

useState correct usage with function initializer

Use `useState('counter', () => 0)` to properly initialize state. The second parameter must be a function that returns the initial value, not the value itself.

useState key must be a string

The useState() composable requires the first argument to be a non-empty string. This key identifies the shared state across the app and in the hydration payload. If called with a key that is not a string, the error E7009 is raised.

useState correct usage example

const counter = useState('counter', () => 0)

Give your agent this brain