-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKitties.js
104 lines (86 loc) · 2.74 KB
/
Kitties.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, { useEffect, useState } from 'react';
import { Form, Grid } from 'semantic-ui-react';
import { useSubstrate } from './substrate-lib';
import { TxButton } from './substrate-lib/components';
import KittyCards from './KittyCards';
// Construct a Kitty ID from storage key
const convertToKittyHash = entry =>
`0x${entry[0].toJSON().slice(-64)}`;
// Construct a Kitty object
const constructKitty = (hash, { dna, price, gender, owner }) => ({
id: hash,
dna,
price: price.toJSON(),
gender: gender.toJSON(),
owner: owner.toJSON()
});
// Use React hooks
export default function Kitties (props) {
const { api, keyring } = useSubstrate();
const { accountPair } = props;
const [kittyHashes, setKittyHashes] = useState([]);
const [kitties, setKitties] = useState([]);
const [status, setStatus] = useState('');
// snip
// Subscription function for setting Kitty IDs
const subscribeKittyCnt = () => {
let unsub = null
const asyncFetch = async () => {
// Query KittyCnt from runtime
unsub = await api.query.substrateKitties.kittyCnt(async cnt => {
// Fetch all Kitty objects using entries()
const entries = await api.query.substrateKitties.kitties.entries()
// Retrieve only the Kitty ID and set to state
const hashes = entries.map(convertToKittyHash)
setKittyHashes(hashes)
})
}
asyncFetch()
// return the unsubscription cleanup function
return () => {
unsub && unsub()
}
}
// Subscription function to construct a Kitty object
const subscribeKitties = () => {
let unsub = null
const asyncFetch = async () => {
// Get Kitty objects from storage
unsub = await api.query.substrateKitties.kitties.multi(kittyHashes, kitties => {
// Create an array of Kitty objects from `constructKitty`
const kittyArr = kitties.map((kitty, ind) =>
constructKitty(kittyHashes[ind], kitty.value)
)
// Set the array of Kitty objects to state
setKitties(kittyArr)
})
}
asyncFetch()
// return the unsubscription cleanup function
return () => {
unsub && unsub()
}
}
useEffect(subscribeKittyCnt, [api, keyring])
useEffect(subscribeKitties, [api, kittyHashes])
return (
<Grid.Column width={16}>
<h1>Kitties</h1>
<KittyCards kitties={kitties} accountPair={accountPair} setStatus={setStatus}/>
<Form style={{ margin: '1em 0' }}>
<Form.Field style={{ textAlign: 'center' }}>
<TxButton
accountPair={accountPair} label='Create Kitty' type='SIGNED-TX' setStatus={setStatus}
attrs={{
palletRpc: 'substrateKitties',
callable: 'createKitty',
inputParams: [],
paramFields: []
}}
/>
</Form.Field>
</Form>
<div style={{ overflowWrap: 'break-word' }}>{status}</div>
</Grid.Column>
)
};