import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
counter: 0,
}
},
})
export const useStore = defineStore('main', {
state: () => {
return {
counter: 0,
}
},
actions: {
increment() {
this.counter++
},
},
})
export const useStore = defineStore('tractors', {
state: () => {
return {
tractors: [],
loading: false,
error: null,
}
},
})
export const useStore = defineStore('tractors', {
state: () => {
return {
tractors: [],
loading: false,
error: null,
}
},
actions: {
async fetchTractors() {
this.loading = true
try {
const response = await getTractors()
this.tractors = response.data
} catch (error) {
this.error = error
}
this.loading = false
},
},
})
import { useStore } from '../store'
const store = useStore()
store.fetchTractors()
export const useStore = defineStore('tractors', {
state: () => {
/* ... */
},
actions: {
/* ... */
},
getters: {
fetchStarted: (state) => state.tractors.length > 0 || state.loading,
}
})
if (!store.fetchStarted) {
store.fetchTractors()
}
[
{
id: '1',
name: 'John Deere 7R 350 AutoPowr',
image_url: 'https://tractors.com/1',
},
{
id: '2',
name: 'Reform Metrac H75 Pro',
image_url: 'https://tractors.com/2',
}
]
[
{
id: '1',
name: 'John Deere 7R 350 AutoPowr',
image_url: 'https://tractors.com/1',
engine: '9-litre, 6-cylinder DPS',
rated_power: '350hp',
description:
'The low overall machine weight of the 7R Series and high horsepower ...',
},
{
id: '2',
name: 'Reform Metrac H75 Pro',
image_url: 'https://tractors.com/2',
}
]
actions: {
async fetchTractor(id) {
this.loading = true
try {
const response = await getTractor(id)
const existingTractor = this.tractors.find((t) => t.id === id)
if (existingTractor) {
const { description, engine, rated_power } = response.data
existingTractor.description = description
existingTractor.engine = engine
existingTractor.rated_power = rated_power
} else {
this.tractors.push(response.data)
}
} catch (error) {
this.error = error
}
this.loading = false
},
},
actions: {
async fetchTractors() {
this.loading = true
try {
const response = await getTractors()
this.tractors = response.data
} catch (error) {
this.error = error
}
this.loading = false
},
},
actions: {
async fetchTractors() {
this.loading = true
try {
const response = await getTractors()
this.tractors = response.data.reduce((acc, current) => {
const existingTractor = acc.find((t) => t.id === current.id)
if (!existingTractor) {
return [...acc, current]
}
return acc
}, this.tractors)
} catch (error) {
this.error = error
}
this.loading = false
},
},
getters: {
fetchStarted: (state) => state.tractors.length > 0 || state.loading,
}
getters: {
fetchStarted: (state) => state.tractors.length > 1 || state.loading,
}