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('characters', {
state: () => {
return {
characters: [],
loading: false,
error: null,
}
},
})
export const useStore = defineStore('characters', {
state: () => {
return {
characters: [],
loading: false,
error: null,
}
},
actions: {
async fetchCharacters() {
this.loading = true
try {
const response = await getCharacters()
this.characters = response.data
} catch (error) {
this.error = error
}
this.loading = false
},
},
})
import { useStore } from '../store'
const store = useStore()
store.fetchCharacters()
export const useStore = defineStore('characters', {
state: () => {
/* ... */
},
actions: {
/* ... */
},
getters: {
fetchStarted: (state) => state.characters.length > 0 || state.loading,
}
})
if (!store.fetchStarted) {
store.fetchCharacters()
}
[
{
id: "1",
name: "Alice",
image_url: "https://image1.png",
},
{
id: "2",
name: "The Cheshire Cat",
image_url: "https://image2.png",
},
]
[
{
id: "1",
name: "Alice",
image_url: "https://image1.png",
occupation: "White Pawn",
address: "London",
description: "Alice is a very lovely, pretty and beautiful young girl..."
},
{
id: "2",
name: "The Cheshire Cat",
image_url: "https://image2.png",
},
]
actions: {
async fetchCharacter(id) {
this.loading = true
try {
const response = await getCharacter(id)
const existingCharacter = this.characters.find((t) => t.id === id)
if (existingCharacter) {
const { description, address, occupation } = response.data
existingCharacter.description = description
existingCharacter.address = address
existingCharacter.occupation= occupation
} else {
this.characters.push(response.data)
}
} catch (error) {
this.error = error
}
this.loading = false
},
},
actions: {
async fetchCharacters() {
this.loading = true
try {
const response = await getCharacters()
this.characters = response.data
} catch (error) {
this.error = error
}
this.loading = false
},
},
actions: {
async fetchCharacters() {
this.loading = true
try {
const response = await getCharacters()
this.characters = response.data.reduce((acc, current) => {
const existingCharacter = acc.find((t) => t.id === current.id)
if (!existingCharacter) {
return [...acc, current]
}
return acc
}, this.characters)
} catch (error) {
this.error = error
}
this.loading = false
},
},
getters: {
fetchStarted: (state) => state.characters.length > 0 || state.loading,
}
getters: {
fetchStarted: (state) => state.characters.length > 1 || state.loading,
}