* Add tutorial step 001 * Update LICENSE header * Query storage via HOC * Tut 003, read proposals * Tut 004 replacing HOC * Pull Intentions & Proposals together * Add final image * Cleanup unused methods * Source links * Remove unused var
2.8 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> {
...
componentDidMount () {
this.subscribeProposals();
}
// TODO We should unsubscribe from subscriptions
subscribeProposals () {
const { api } = this.props;
const key = createStorageKey(method)();
const transform = storageTransform(method);
api.state
.getStorage(key)
.subscribe((value) => {
this.setState({
proposals: (transform(value, 0) as any[])
.reduce((proposals, [propIdx, proposal, accountId]) => {
const address = encodeAddress(accountId);
if (!proposals[address]) {
proposals[address] = [propIdx];
} else {
proposals[address].push(propIdx);
}
return proposals;
}, {})
});
});
}
...
}
export default withApi(Comp);
walk-through
Since we are working on a slightly lower level now, a couple of things happen.
Unlike the case where we use an HOC, we need to manually create the actual storage key (as encoded) before calling the API. the createStorageKey(<method>)(<params>) function does that for us. In this case the storage entry doesn't require any params (as opposed to e.g. staking.freeBalanceOf). This encoding takes the method, params, applys the correct prefixes and hashes the result to form a key that is known to the staorage.
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.
We use the API provided on the component props, as 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.
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.
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.