Skip to content

Instantly share code, notes, and snippets.

@edisdev
Created June 28, 2022 20:35
Show Gist options
  • Save edisdev/69381ae3d2a55602f9656df33a744eec to your computer and use it in GitHub Desktop.
Save edisdev/69381ae3d2a55602f9656df33a744eec to your computer and use it in GitHub Desktop.
Pinia Store Example
import { defineStore } from 'pinia'
export const useProductStore = defineStore('product', {
state: () => ({
products: [],
isFetchingProducts: false
}),
getters: {
categories () {
const categoryList = this.products
.map(p => p.category)
.filter((v, i, a) => a.indexOf(v) === i)
return categoryList.reduce((obj, category) => {
obj[category] = this.products.filter(p => p.category === category)
return obj
}, {})
}
},
actions: {
async fetchProducts () {
this.isFetchingProducts = true
try {
const result = await fetch('https://fakestoreapi.com/products')
const data = await result.json()
this.products = data
} catch (error) {
console.log(error)
} finally {
this.isFetchingProducts = false
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment