Created
June 28, 2022 20:35
-
-
Save edisdev/69381ae3d2a55602f9656df33a744eec to your computer and use it in GitHub Desktop.
Pinia Store Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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