Skip to content

Latest commit

 

History

History
85 lines (57 loc) · 3.03 KB

tut-002.md

File metadata and controls

85 lines (57 loc) · 3.03 KB

storage via HOC

In the previous section we setup a basic application framework in app-example. Here we will continute adding some useful queries using bare-bones UI components.

In substrate chains, the storage (state) is exposed via API, allowing any app to perform queries against the current (and previous) states. Here we will use some built-in components to perform a query over the intentions, displaying the results.

creating a component

Here we are creating a component that will attach to a specific storage entry, and display any changes as they happen on-chain. For this example, we are interested in the intentions storage area, i.e. those accounts that wish to participate in staking.

Initially we will just create it, and then walk through what actually happens. In comp-002.tsx we have -

import React from 'react';

import storage from '@polkadot/storage';
import withStorageDiv from '@polkadot/ui-react-rx/with/storageDiv';
import encodeAddress from '@polkadot/util-keyring/address/encode';

const method = storage.staking.public.intentions;

const Comp: React.ComponentType<any> = withStorageDiv(method)(
  (value: Uint8Array[]): string => {
    if (!value || !value.length) {
      return 'No intentions found';
    }

    return value.map(encodeAddress).join(', ');
  }
);

export default Comp;

Additionally, we change our entry-point to import this component.

import React from 'react';

import Comp from './comp-002';

export default class App extends React.PureComponent<any> {
  render () {
    return (
      <Comp />
    );
  }
}

Now going to the app via localhost:3000/#/example renders a list of accounts.

walk-through

So what have we done. First off, we import all available storage entries and select the method we are interested in, i.e.

import storage from '@polkadot/storage';

const method = storage.staking.public.intentions;

Storage entries can be explored via the storage app and will always be (in code) storage.<section>.public.<method>. These are all defined in @polkadot/storage

Next up we use an HOC helper withStorageDiv which basically takes a storage method and with the specified renderer wraps it in a Div.

import withStorageDiv from '@polkadot/ui-react-rx/with/storageDiv';

const Comp: React.ComponentType<any> = withStorageDiv(method)(
  (value: Uint8Array[]): string => {
    ...
  }
);

Here the storage query will return an Uint8Array[], or rather an array of Accounts as used internally. These Accounts however are a list of the actual publicKeys, so for display we convert them with a formatter,

return value.map(encodeAddress).join(', ');

next steps

At this point we have, with minimal effort, used some HOC helpers to display information from a storage area. Next up we will actually pull this together and do the same query directly via the API.