In this example we use
Core methods for connecting to the server using WebSockets.
We implement a button with counters like in Using widgets. The difference is that the state of the counters is kept in the simple Node.js (Express) server.
Here is the initial code for this example:
- We add the server's URL to
It's possible to set different URLs for
./src/index.ts we get this URL from the config:
- Then we have to create a connection with the server.
Core.connecthas its own state, so we have to provide the default state and its type or interface.
To understand how the dapplet's state works read the article Shared State.
In this simple example we can only use
connection's state. But in your dapplet you might want to use one complex state for the entire app.
So let's create a common state.
Here we use the same interface and default state, but in your dapplet you can use other ones.
- In the config we get
ctx. We can use
ctx.idas a key in our states. If we use the common state, we can pass observable value of the server's state to it.
- In the
button's DEFAULT state we pass the observable counter to the label and in
execincrease its value with a click. We implement the function that increases the counters on the server side. In the dapplet we call this function by using the
sendmethod. The first parameter is the name of the function and the second is a parameter for the server's function. In our case it's context ID.
Note that we don't pass the entire observable state's
amount, but instead it's value to the
label. This is because this value is observable server's amount.
When we directly use
server.state[ctx.id].amount without the common state we don't have to get its value here.
This is the entire
- Add a storage for the counters in
- Initialize a counter for the current tweet.
- Send the counter in
- Send the counter in a callback.
- Implement the counter increment.
Here is the result code of the example:
Run the dapplet:
if an error occurs in the 'src/index.ts' , delete the 'package-lock.json' and run npm i