Working with REST API - XMPieLab/uStore-NG GitHub Wiki

uStore NG provides an API platform that enables you to access uStore data directly from the uStore server. In addition, uStore library provides easy access, using JavaScript, to the APIs. This capability allows you to manage data and display it in the Storefront.

To get to the API documentation go to http://<uStoreServer>/ustorerestapi

Import

import {UStoreProvider} from '@ustore/core'

Example: retrieving a category model from the API

const category = UStoreProvider.api.categories.getCategory(categoryID)

All functions are asynchronous, so you can use the async/await practice in order to make the functions synchronous. The UStoreProvider.api exposes JavaScript functions that are equivalent to the APIs in the uStore server.

Get the latest API from {ustore-server}/uStoreRestAPI.

Fetch data before page load

To load data when the page loads we use getInitialProps, which is an async static method.
It can asynchronously fetch data from any API (uStore and external APIs), and its returning values will populate the custom state.

You can use getInitialProps only for pages that reside in the src/routes folder (not in the components folder).

Let’s look at the category page:

Category.getInitialProps = async (ctx) => {
  const {query: { id: categoryFriendlyID}} = ctx
  let {currentCategory} = UStoreProvider.state.customState.get()

  if (!currentCategory || categoryFriendlyID !== currentCategory.FriendlyID.toString()) {
    const categoryID = await UStoreProvider.api.categories.getCategoryIDByFriendlyID(categoryFriendlyID)
    currentCategory = await UStoreProvider.api.categories.getCategory(categoryID)
    const {Categories: subCategories} = await UStoreProvider.api.categories.getSubCategories(categoryID)
    const {Products: categoryFeaturedProducts} = await UStoreProvider.api.products.getProducts(categoryID, 1)
    return {
      categoryFeaturedProducts,
      currentCategory,
      subCategories
    }
  }
}

You can see that the getInitialProps function gets data from the API (or from an external server) and returns an object. This object is populated to the custom state.

The custom state will now look as follows (it can have additional data):

customState={
   categoryFeaturedProducts:'...',
   currentCategory:'...',
   subCategories:'...' 
}