Skip to content

Instantly share code, notes, and snippets.

@handrihmw
Created August 10, 2023 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save handrihmw/306cb9ec0fa22989f520cd95ac43bf5f to your computer and use it in GitHub Desktop.
Save handrihmw/306cb9ec0fa22989f520cd95ac43bf5f to your computer and use it in GitHub Desktop.
Pinia Vue 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