Created
August 10, 2023 03:02
-
-
Save handrihmw/306cb9ec0fa22989f520cd95ac43bf5f to your computer and use it in GitHub Desktop.
Pinia Vue 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