Skip to content

Commit

Permalink
Added useCategories() composable
Browse files Browse the repository at this point in the history
  • Loading branch information
markus-gx committed Nov 22, 2022
1 parent aa3a0d8 commit 675ebab
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 5 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,23 @@ await useAsyncData('first-page', async () => await fetch({
</script>
```

#### Fetch All Categories
To fetch all categories from swell just destructure the composable and use the result or `categories` as `ComputedRef`.

```vue
<ul>
<li v-for="c in categories" :key="c.id">
{{ c.name }}
</li>
</ul>
<script setup>
const { categories, fetchCategories } = useSwellCategories()
await useAsyncData('categories', async () => await fetchCategories())
</script>
```


**And more to come soon!**

## Development
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nuxt-swell",
"version": "0.1.2",
"version": "0.1.3",
"license": "MIT",
"type": "module",
"repository": {
Expand Down
13 changes: 12 additions & 1 deletion playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,24 @@
</nuxt-link>
</li>
</ul>
<hr>
<h2>Categories test</h2>
<ul>
<li v-for="c in categories" :key="c.id">
{{ c.name }}
</li>
</ul>
</div>
</template>

<script setup>
import { useAsyncData } from 'nuxt/app'
import useSwellProducts from '../../dist/runtime/composables/useSwellProducts'
import useSwellCategories from '../../dist/runtime/composables/useSwellCategories'
const { list, fetch } = await useSwellProducts('first-page')
const { list, fetch } = useSwellProducts('first-page')
await useAsyncData('first-page', async () => await fetch())
const { categories, fetchCategories } = useSwellCategories()
await useAsyncData('categories', async () => await fetchCategories())
</script>
11 changes: 8 additions & 3 deletions src/runtime/composables/useSwellCategories.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { useState } from '#app'
import { computed } from 'vue'
import { computed, ComputedRef } from 'vue'
import { Category } from '../../types/swell-js'
import useSwell from './useSwell'

export default function () {
export type UseCategoriesReturnType = {
categories: ComputedRef<Category[]>,
fetchCategories: () => Promise<Category[]>
}

export default function (): UseCategoriesReturnType {
const result = useState<Category[]>('categories', () => [])

const fetch = async (): Promise<Category[]> => {
Expand All @@ -14,6 +19,6 @@ export default function () {

return {
categories: computed(() => result.value),
fetch
fetchCategories: fetch
}
}

0 comments on commit 675ebab

Please sign in to comment.