Skip to content

Commit

Permalink
docs: add composables docs (#1062)
Browse files Browse the repository at this point in the history
  • Loading branch information
filipsobol committed May 27, 2022
1 parent d2cbc73 commit 774cf9f
Show file tree
Hide file tree
Showing 76 changed files with 449 additions and 150 deletions.
48 changes: 8 additions & 40 deletions docs/.vuepress/config.js
Expand Up @@ -67,6 +67,14 @@ module.exports = {
['/getting-started/configure-integration', 'Configuring Vue Storefront'],
],
},
{
title: 'Composition',
collapsable: false,
children: [
['/composition/composables', 'Composables'],
['/composition/list-of-composables', 'List of composables'],
],
},
{
title: 'Guides',
collapsable: false,
Expand All @@ -86,46 +94,6 @@ module.exports = {
['/guide/ssr', 'Server Side Rendering Cache'],
],
},
{
title: 'Composables',
children: [
['/api-reference/magento-theme.useaddresses', 'useAddresses'],
['/api-reference/magento-theme.useapi', 'useApi'],
['/api-reference/magento-theme.usebilling', 'useBilling'],
['/api-reference/magento-theme.usecart', 'useCart [Deprecated]'],
['/api-reference/magento-theme.usecategory', 'useCategory [Deprecated]'],
['/api-reference/magento-theme.usecategorysearch', 'useCategorySearch'],
['/api-reference/magento-theme.useconfig', 'useConfig'],
['/api-reference/magento-theme.usecontent', 'useContent'],
['/api-reference/magento-theme.usecountrysearch', 'useCountrySearch'],
['/api-reference/magento-theme.usecurrency', 'useCurrency'],
['/api-reference/magento-theme.useexternalcheckout', 'useExternalCheckout'],
['/api-reference/magento-theme.usefacet', 'useFacet [Deprecated]'],
['/api-reference/magento-theme.useforgotpassword', 'useForgotPassword [Deprecated]'],
['/api-reference/magento-theme.usegetshippingmethods', 'useGetShippingMethods [Deprecated]'],
['/api-reference/magento-theme.useguestuser', 'useGuestUser [Deprecated]'],
['/api-reference/magento-theme.useimage', 'useImage'],
['/api-reference/magento-theme.usemagentoconfiguration', 'useMagentoConfiguration'],
['/api-reference/magento-theme.usemakeorder', 'useMakeOrder [Deprecated]'],
['/api-reference/magento-theme.usenewsletter', 'useNewsletter'],
['/api-reference/magento-theme.usepaymentprovider', 'usePaymentProvider [Deprecated]'],
['/api-reference/magento-theme.useproduct', 'useProduct [Deprecated]'],
['/api-reference/magento-theme.userelatedproducts', 'useRelatedProducts [Deprecated]'],
['/api-reference/magento-theme.usereview', 'useReview'],
['/api-reference/magento-theme.useshipping', 'useShipping [Deprecated]'],
['/api-reference/magento-theme.useshippingprovider', 'useShippingProvider'],
['/api-reference/magento-theme.usestore', 'useStore'],
['/api-reference/magento-theme.useuihelpers', 'useUiHelpers'],
['/api-reference/magento-theme.useuinotification', 'useUiNotification'],
['/api-reference/magento-theme.useuistate', 'useUiState'],
['/api-reference/magento-theme.useupsellproducts', 'useUpsellProducts [Deprecated]'],
['/api-reference/magento-theme.useurlresolver', 'useUrlResolver'],
['/api-reference/magento-theme.useuser', 'useUser [Deprecated]'],
['/api-reference/magento-theme.useuseraddress', 'useUserAddress'],
['/api-reference/magento-theme.useuserorder', 'useUserOrder [Deprecated]'],
['/api-reference/magento-theme.usewishlist', 'useWishlist [Deprecated]'],
],
},
{
title: 'Reference',
children: [
Expand Down
Binary file added docs/assets/images/useUser-composable-anatomy.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/images/useUser-load-flow.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
112 changes: 112 additions & 0 deletions docs/composition/composables.md
@@ -0,0 +1,112 @@
# Composables

## Prerequisites

Composables use the Composition API introduced in Vue 3 but are also made available via plugins in Vue 2. If you are not familiar with it, see the [Composition API guide](https://docs.vuestorefront.io/v2/composition/composition-api.html).

## What are composable?

Composables are functions with an **internal state** that changes over time and **methods** that modify this state. You cannot directly modify the state but only by calling these methods. However, because the state is reactive — thanks to the Compositions API available in Vue applications — you can watch and react to these changes when necessary to update the UI or perform other operations.

This pattern encapsulates the state and business logic and exposes it through easy-to-use methods.

## Anatomy of a composable

Most composables consist of one or more of the following:

- **Primary state** - read-only state of the composable. You cannot update it directly but only by calling composable **methods**.
- **Supportive state** - additional read-only state for values such as the status of the requests or errors.
- **Methods** - functions that update the primary and supportive states. These methods usually call API endpoints but can also manage cookies or call methods from other composables.

To make composables easily distinguishable from standard methods, we follow the popular convention of names starting with "use".

### How does it look like in practice?

Let's take a closer look at how it might look like using the [useUser](/api-reference/magento-theme.useuserinterface.html) composable as an example:

<img
src="../assets/images/useUser-composable-anatomy.png"
alt="Anatomy of the useUser composable"
style="display: block; margin: 0 auto;">

In this example:

- the `user` property is the primary state,
- the `loading` and `error` properties represent the supportive state,
- the `load`, `register`, `login`, `logout`, and `changePassword` are methods.

## Usage

Let's see how you can use the [useUser](/api-reference/magento-theme.useuserinterface.html) composable to load the current user's data:

```vue
<script>
import { useUser } from '~/composables/useReview';
import { useFetch } from '@nuxtjs/composition-api';
export default {
setup() {
const { load, user } = useUser();
useFetch(async () => {
await load();
});
return {
user
};
}
};
</script>
```

Let's go step by step through this example to understand what's going on:

1. We begin by extracting needed methods and state variables from the composable.
2. Next, we call the asynchronous `load` method within the `useFetch` hook to load user data.
3. Finally, we return the `user` object from the `setup` method to make it available in the components `<template>`.

While it's okay to destructure composable like we did in step 1, you should **not** destructure read-only state, such as the `user` or `error` properties, because resulting variables will not be reactive and won't update.

```javascript
// ❌ Destructuring `user` will create variables that aren't reactivity and don't update
const { user: { value: { firstname } } } = useUser();

// ✔️ Using `computed` will make the variable react to changes in the `user` object
const { user } = useUser();
const firstname = computed(() => user.value.firstname);
```

This raises two questions:

1. What is the `useFetch`, and what does it do?
2. What happened when we called the `load` method?

### `useFetch` and other hooks for fetching data

There are many hooks available in Composition API, but let's only focus on the most common ones used for fetching data:

- The [useFetch](https://composition-api.nuxtjs.org/lifecycle/usefetch/) and [useAsync](https://composition-api.nuxtjs.org/API/useAsync) are Nuxt-specific hooks called on the server-side when rendering the route and on the client-side when navigating between pages.
- The `onMounted` is a lifecycle hook called **only on the client-side** after the browser loads the page.
- The `onServerPrefetch` is a lifecycle hook called **only on the server-side** when rendering the route.

You can use one or more hooks simultaneously, even in the same component.

### Internals of the `load` method

You might be wondering what happened within the composable when we called the `load` method in the example above. The behavior of methods is different between composables, but in the case of the `useUser` composable, the `load` method updated the `loading`, `error`, and `user` properties to reflect the current state, and later the result of the API call corresponding to this method.

<img
src="../assets/images/useUser-load-flow.png"
alt="Flow of the load method from the useUser composable"
style="display: block; margin: 0 auto;">

1. It set the `loading` property to `true`.
2. It called the corresponding API endpoint to load the current user's data.
- if the request succeeded, it updated the `user` property,
- otherwise, it added the error message to the `error` property.
3. It set the `loading` property to `false`.

## What's next?

Now that you understand what composables are, you should see the [List of composables](./list-of-composables.html) and their options.
211 changes: 211 additions & 0 deletions docs/composition/list-of-composables.md
@@ -0,0 +1,211 @@
# List of composables

## `useAddresses`

Allows loading and manipulating addresses of the current user. These addresses can be used for both billing and shipping.

See the [UseAddressesInterface](/api-reference/magento-theme.useaddressesinterface.html) for more information.

## `useApi`

Allows executing arbitrary GraphQL queries and mutations.

See the [UseApiInterface](/api-reference/magento-theme.useapiinterface.html) for more information.

## `useBilling`

Allows loading and saving billing information of the current cart.

See the [UseBillingInterface](/api-reference/magento-theme.usebillinginterface.html) for more information.

## `useCart`

Allows loading and manipulating cart of the current user.

See the [UseCartInterface](/api-reference/magento-theme.usecartinterface.html) for more information.

## `useCategory`

Allows loading categories from Magento API. It is commonly used in navigation menus, and provides the load function and refs for the categories, loading and error.

See the [UseCategoryInterface](/api-reference/magento-theme.usecategoryinterface.html) for more information.

## `useCategorySearch`

Allows searching for categories. It is commonly used in subtrees navigation.

See the [UseCategorySearchInterface](/api-reference/magento-theme.usecategorysearchinterface.html) for more information.

## `useConfig`

Allows interacting with the store configuration.

See the [UseConfigInterface](/api-reference/magento-theme.useconfiginterface.html) for more information.

## `useContent`

Allows loading CMS Pages or Blocks from Magento API.

See the [UseContentInterface](/api-reference/magento-theme.usecontentinterface.html) for more information.

## `useCountrySearch`

Allows fetching a list of countries or a single country by ID

See the [UseCountrySearchInterface](/api-reference/magento-theme.usecountrysearchinterface.html) for more information.

## `useCurrency`

Allows loading and changing the currency.

See the [UseCurrencyInterface](/api-reference/magento-theme.usecurrencyinterface.html) for more information.

## `useExternalCheckout` (Work in progress)

Allows redirecting to external checkout process. It depends on the [magento2-external-checkout repository](https://github.com/Vendic/magento2-external-checkout).

See the [UseExternalCheckoutInterface](/api-reference/magento-theme.useexternalcheckoutinterface.html) for more information.

## `useFacet`

Allows searching for products with pagination, totals and sorting options.

See the [UseFacetInterface](/api-reference/magento-theme.usefacetinterface.html) for more information.

## `useForgotPassword`

Allows to request a password reset email and to set a new password to a user.

Se the [UseForgotPasswordInterface](/api-reference/magento-theme.useforgotpasswordinterface.html) for more information.

## `useGetShippingMethods`

Allows fetching shipping methods available for a given cart.

See the [UseGetShippingMethodsInterface](/api-reference/magento-theme.usegetshippingmethodsinterface.html) for more information.

## `useGuestUser`

Allows to attach a guest cart to a user.

See the [UseGuestUserInterface](/api-reference/magento-theme.useguestuserinterface.html) for more information.

## `useImage`

Allows extracting image paths from magento URL.

See the [UseImageInterface](/api-reference/magento-theme.useimageinterface.html) for more information.

## `useMagentoConfiguration`

Allows getting the Magento's major definitions, e.g., the selected currency, store, locale, and config object.

See the [UseMagentoConfigurationInterface](/api-reference/magento-theme.usemagentoconfigurationinterface.html) for more information.

## `useMakeOrder`

Allows making an order from a cart.

See the [UseMakeOrderInterface](/api-reference/magento-theme.usemakeorderinterface.html) for more information.

## `useNewsletter`

Allows updating the subscription status of an email in the newsletter.

See the [UseNewsletterInterface](/api-reference/magento-theme.usenewsletterinterface.html) for more information.

## `usePaymentProvider`

Allows loading the available payment methods for current cart, and selecting (saving) one of them.

See the [UsePaymentProviderInterface](/api-reference/magento-theme.usepaymentproviderinterface.html) for more information.

## `useProduct`

Allows loading product details or list with params for sorting, filtering and pagination.

See the [UseProductInterface](/api-reference/magento-theme.useproductinterface.html) for more information.

## `useRelatedProducts`

Allows searching for related products with params for sort, filter and pagination.

See the [UseRelatedProductsInterface](/api-reference/magento-theme.userelatedproductsinterface.html) for more information.

## `useReview`

Allows loading and adding product reviews.

See the [UseReviewInterface](/api-reference/magento-theme.usereviewinterface.html) for more information.

## `useShipping`

Allows loading the shipping information for the current cart and saving (selecting) other shipping information for the same cart.

See the [UseShippingInterface](/api-reference/magento-theme.useshippinginterface.html) for more information.

## `useShippingProvider`

Allows loading the shipping provider for the current cart and saving (selecting) other shipping provider for the same cart.

See the [UseShippingProviderInterface](/api-reference/magento-theme.useshippingproviderinterface.html) for more information.

## `useStore`

Allows loading and changing currently active store.

See the [UseStoreInterface](/api-reference/magento-theme.usestoreinterface.html) for more information.

## `useUiHelpers`

Allows handling the parameters for filtering, searching, sorting and pagination in the URL search/query params.

See the [UseUiHelpersInterface](/api-reference/magento-theme.useuihelpersinterface.html) for more information.

## `useUiNotification`

Allows managing and showing notifications to the user.

See the [UseUiNotificationInterface](/api-reference/magento-theme.useuinotificationinterface.html) for more information.

## `useUiState`

Global store for managing UI state.

See the [UseUiStateInterface](/api-reference/magento-theme.useuistateinterface.html) for more information.

## `useUpsellProducts`

Allows loading upsell products.

See the [UseUpsellProductsInterface](/api-reference/magento-theme.useupsellproductsinterface.html) for more information.

## `useUrlResolver`

Allows searching the resolver for current route path (URL).

See the [UseUrlResolverInterface](/api-reference/magento-theme.useurlresolverinterface.html) for more information.

## `useUser`

Allows loading and manipulating data of the current user.

See the [UseUserInterface](/api-reference/magento-theme.useuserinterface.html) for more information.

## `useUserAddress`

Allows loading and manipulating addresses of the current user.

See the [UseUserAddressInterface](/api-reference/magento-theme.useuseraddressinterface.html) for more information.

## `useUserOrder`

Allows fetching customer orders.

See the [UseUserOrderInterface](/api-reference/magento-theme.useuserorderinterface.html) for more information.

## `useWishlist`

Allows loading and manipulating wishlist of the current user.

See the [UseWishlistInterface](/api-reference/magento-theme.usewishlistinterface.html) for more information.

0 comments on commit 774cf9f

Please sign in to comment.