State machine

Now let’s try to have the button change its appearance when clicked.

Here is the initial code for this example: ex02-state-machine-exercise.

Here is src/index.ts:

1import {} from '@dapplets/dapplet-extension'
2import COOL_BADGE_IMG from './icons/smile19.png'
3// import ANGRY_BADGE_IMG from './icons/angry-smile19.png'
4
5@Injectable
6export default class TwitterFeature {
7 @Inject('twitter-config.dapplet-base.eth')
8 public adapter
9
10 activate() {
11 const { button } = this.adapter.exports
12 this.adapter.attachConfig({
13 POST: () =>
14 button({
15 initial: 'DEFAULT',
16 DEFAULT: {
17 label: 'Fake',
18 img: COOL_BADGE_IMG,
19 // LP: 2. Add function toggling the button state
20
21 // LP end
22 },
23 // LP: 1. Add another state to the button
24
25 // LP end
26 }),
27 })
28 }
29}

Firstly, add another state with a different badge to the button.

1ANOTHER: {
2 label: 'FAKE!!!',
3 img: ANGRY_BADGE_IMG,
4 exec: (_, me) => (me.state = 'DEFAULT'),
5},

Secondly, implement toggling states on button click.

exec: (_, me) => (me.state = 'ANOTHER'),

Result:

1import {} from '@dapplets/dapplet-extension'
2import COOL_BADGE_IMG from './icons/smile19.png'
3import ANGRY_BADGE_IMG from './icons/angry-smile19.png'
4
5@Injectable
6export default class TwitterFeature {
7 @Inject('twitter-config.dapplet-base.eth')
8 public adapter
9
10 activate() {
11 const { button } = this.adapter.exports
12 this.adapter.attachConfig({
13 POST: () =>
14 button({
15 initial: 'DEFAULT',
16 DEFAULT: {
17 label: 'Fake',
18 img: COOL_BADGE_IMG,
19 // LP: 2. Add function toggling the button state
20 exec: (_, me) => (me.state = 'ANOTHER'),
21 // LP end
22 },
23 // LP: 1. Add another state to the button
24 ANOTHER: {
25 label: 'FAKE!!!',
26 img: ANGRY_BADGE_IMG,
27 exec: (_, me) => (me.state = 'DEFAULT'),
28 },
29 // LP end
30 }),
31 })
32 }
33}

Here is our example’s result code: ex02-state-machine-solution.

Run the dapplet:

npm i
npm start

In the browser:

video

If you don't know how to run a dapplet in your browser, see Get Started.