We use cookies to enhance your experience on the site
CodeWorlds

State in Pinia

State is reactive data stored in the store - like the main computer's database at NOVA LAB. Every sensor reading, every mission parameter is recorded here and available to all station modules.

Defining State

In Composition API style, state is simply

ref()
and
reactive()
:

1import { defineStore } from 'pinia'
2import { ref, reactive } from 'vue'
3
4export const useResourceStore = defineStore('resources', () => {
5  // Simple values - ref()
6  const oxygen = ref(98.5)
7  const water = ref(1250)
8  const energy = ref(87)
9  const isEmergency = ref(false)
10
11  // Objects - reactive() or ref()
12  const crew = reactive({
13    commander: 'Nova',
14    engineer: 'Atlas',
15    scientist: 'Darwin'
16  })
17
18  // Arrays
19  const logs = ref([])
20
21  return { oxygen, water, energy, isEmergency, crew, logs }
22})

Modifying State

State can be modified directly in actions or from a component:

1export const useResourceStore = defineStore('resources', () => {
2  const oxygen = ref(98.5)
3
4  // Action modifies state
5  function consumeOxygen(amount) {
6    oxygen.value = Math.max(0, oxygen.value - amount)
7  }
8
9  return { oxygen, consumeOxygen }
10})
1<script setup>
2const store = useResourceStore()
3
4// Direct modification (works, but actions are better)
5store.oxygen = 95.0
6
7// Through action (recommended)
8store.consumeOxygen(3.5)
9</script>

$patch - Updating Multiple Properties

$patch
allows updating multiple state properties at once - more efficient than modifying one at a time:

1const store = useResourceStore()
2
3// Object patch - simple override
4store.$patch({
5  oxygen: 95.0,
6  water: 1200,
7  energy: 82,
8  isEmergency: false
9})
10
11// Function patch - for complex operations
12store.$patch((state) => {
13  state.oxygen -= 3.5
14  state.logs.push({
15    type: 'consumption',
16    timestamp: Date.now()
17  })
18})

$reset - Restoring Initial State

In Options API style

$reset()
works automatically. In Composition API you must define your own reset function:

1export const useResourceStore = defineStore('resources', () => {
2  const oxygen = ref(100)
3  const water = ref(1500)
4  const energy = ref(100)
5
6  // Custom reset for Composition API
7  function $reset() {
8    oxygen.value = 100
9    water.value = 1500
10    energy.value = 100
11  }
12
13  return { oxygen, water, energy, $reset }
14})
15
16// Usage
17const store = useResourceStore()
18store.$reset() // Restores initial values

$state - Accessing the Entire State

1const store = useResourceStore()
2
3// Read entire state
4const snapshot = store.$state
5
6// Override entire state
7store.$state = {
8  oxygen: 100,
9  water: 1500,
10  energy: 100,
11  isEmergency: false,
12  crew: { commander: 'Nova' },
13  logs: []
14}
Go to CodeWorlds