ghost-portal/examples/tut-003.md
Jaco Greeff b5c4bc0122
Expand/simplify example: getStorage with keys definitions (#137)
* Update dependencies

* Update examples with simplified storage

* Update dependencies

* Revert tsc location override (check)

* Update dependencies
2018-07-12 19:44:00 +02:00

2.3 KiB

storage via API

In the previous section we have used an HOC to query a storage area. Here we will repeat the same, however this time we will actually use the Rx API to accomplish the same goal.

creating the component

As in previous examples, we will first show the actual component we are using and then delve into how it fits together. Focussing on the meat of the API subscription that happens in the componentMount cycle -

class Comp extends React.PureComponent<ApiProps, State> {
  ...
  // TODO We should unsubscribe from subscriptions
  componentDidMount () {
    this.subscribeProposals();
  }

  subscribeProposals () {
    const { api } = this.props;

    api.state
      .getStorage(storage.democracy.public.proposals)
      .subscribe((value: Array<StorageProposal>) => {
        this.setState({
          proposals: value.reduce((proposals: StateProposals, [propIdx, proposal, accountId]) => {
            const address = encodeAddress(accountId);

            if (!proposals[address]) {
              proposals[address] = [propIdx.toNumber()];
            } else {
              proposals[address].push(propIdx.toNumber());
            }

            return proposals;
          }, {} as StateProposals)
        });
      });
  }
  ...
}

export default withApi(Comp);

walk-through

Since we are working on a slightly lower level now, a couple of things happen.

We use a helper function to decode the values as it comes back - without this we would just have a raw stream of bytes as retrieved from storage. The decding take the raw stream and splits it into a mangeable Array stream (based on trhe number of items), each containing a tuple of data - in this case the PropIndex, Proposal and AccountId.

Finally we loop through the proposals retrieved, indexing these by the actual account address - this information we finally use in the render to update the display.

The API provided on the component props is injected via withApi, to make an API query - subscribing to any updates. As any updates happen to the storage, these will be automatically fed through the API subscriptions, updating the component display.

next up

In the next round, we will extend our subscriptions to also pull the information we previously got via HOC and then map these together.