Category Archives: Uncategorized

mixins and merging (multiple extends in typescript)

ref – https://www.digitalocean.com/community/tutorials/typescript-mixins
https://www.typescriptlang.org/docs/handbook/mixins.html#alternative-pattern

Limitations of Classes

Typescript classes can only extend ONE class

Let’s create an example so that we can demonstrate the value of mixins.

Consider two classes, Car and Lorry, which contain the drive and carry methods respectively.
Then, consider a third class called Truck.
A Truck should include both drive and carry methods:

This will not work because we can only extend a single class.

error: Classes can only extend a single class

1) interfaces can extend multiple classes in TypeScript

When an interface extends a class, it extends ONLY the class members but not their implementation because interfaces don’t contain implementations.

2) Declaration merging

When two or more declarations are declared with the same name, TypeScript merges them into one.

By leveraging these two functionalities in TypeScript, we can create an interface with the same name as Truck and extend both the Car and Lorry classes:

Due to declaration merging, the Truck class will be merged with the Truck interface. This means that the Truck class will now contain the function definitions from both Car and Lorry classes.

And here’s how it’s used:

We can now access the methods in Car and Lorry from a truck object.

Full Example

partialRight + lodash

declare a function:

we give our function to partialRight, along with
the parameter that goes on the right side.

Then use the partial function:

Ricky, Good Morning!

Notice we gave two parameters in the partialRight. This means we already decided that other two parameters (message, extra) have already been dictated when we call partialRight.

Therefore, we have already decided that when using the partial function, we only take ONE parameter (name).

Of course we can change this to only providing the third parameter, and having the user provide two parameters for the partial function.

ricky, Good Morning???

Assertion Operator – typescript

It is a way to tell the compiler

“this expression cannot be null or undefined here, so don’t complain about the possibility of it being null or undefined.”

Sometimes the type checker is unable to make that determination itself.

The bang operator tells the compiler to temporarily relax the “not null” constraint that it might otherwise demand. It says to the compiler: “As the developer, I know better than you that this variable cannot be null right now”.

“Just throw in an exclamation mark to make the code compile” is not very good advice.

The null assertion operator is not one to be used lightly as it is very easy to abuse in ways that will either hide bugs or cause them.

Optional chaining is better when you are trying to call a nested function because it will simply do nothing if something is undefined along the way.

Whereas assertion operator will result in an error being thrown.

Null assertion operators should only ever be used when you know for a fact that a variable could not possibly be null or undefined.

If there’s a chance that that is not the case, do the null check.

Example usage:

When Test’s data property is undefined, we get runtime error. When it is defined, we get “hohoho”.

Optional – typescript

ref – https://www.becomebetterprogrammer.com/typescript-question-mark/

A property can either have a value based on the type:
defined
or
undefined

A key difference here:

When using optional, the property is literally optional. We don’t even need to declare it.

If we were to do use value | undefined, the value may either exist or be undefined, but we MUST make sure the property is there:

Example Usage:

say if we declare null for Test’s datq property:

useEffect

ref – https://www.glennstovall.com/how-to-use-useeffect-and-other-hooks-in-class-components/
https://stackoverflow.com/questions/58579426/in-useeffect-whats-the-difference-between-providing-no-dependency-array-and-an

The first two arguments of useEffect are a function (didUpdate), and an array of dependencies. the didUpdate function can return a function of its own, a cleanUp function. When a component mounts or the dependencies are updated, didUpdate is called. When the component unmounts, cleanUp is called if present.

In React, functional component use useEffect in order to do something “A” when that component has finished rendering its DOM. This is our subscribing effect. React guarantees the DOM has been updated by the time it runs the effects.

Every time we re-render, we schedule a different effect, replacing the previous one.

React cleans up effects from the previous render before running the effects next time.
And the next effect happens when our components update.

By declaring the dependencies array as empty, you only call the didUpdate and cleanUp functions once each. No dependencies mean no updates.

It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again. In other words, Giving it an empty array acts like componentDidMount as in, it only runs once.

However, if you give it no argument like so:

means it runs first on mount and then on every re-render.

Lastly, giving it an array as second argument with any value inside, eg , [variable1] will only execute the code inside your useEffect hook:

  • ONCE on mount
  • whenever that particular variable (variable1) changes

MQTT – Message Queuing Telemetry Transport

ref –

  • https://emqx.medium.com/how-to-use-mqtt-in-the-react-project-1b04d80bd383
  • http://www.steves-internet-guide.com/mqtt/
  • http://www.steves-internet-guide.com/mqtt-hosting-brokers-and-servers/
  • http://www.steves-internet-guide.com/using-javascript-mqtt-client-websockets/
  • https://github.com/chkr1011/MQTTnet/issues/498

demo source

MQTT – Message Queuing Telemetry Transport.

The best way of understanding MQTT is to use it, and to do that you need two things:

  • An MQTT broker
  • An MQTT client

Rather than installing your own broker (mosquitto) I recommend that you first start with a public test broker like test.mosquitto.org or broker.emqx.io

its protocol may be: ws://
and port 8083

Now that we have a broker that will take in our messages…we should implement the MQTT client.

Implementing the MQTT client

Create a React Native App.


npx create-react-app react-mqtt-test –template typescript
npm install –save typescript @types/node @types/react @types/react-dom @types/jest
npm install mqtt –save

Note that you will encounter error
ERROR in ./node_modules/mqtt/lib/connect/index.js 7:12-26
Module not found: Error: Can’t resolve ‘url’ in ‘/Users/ricky_tsao/Desktop/jwt-react-rtk-query/node_modules/mqtt/lib/connect’

npm install url

(https://stackoverflow.com/questions/54392956/react-native-mqtt-module-url-does-not-exist-in-the-haste-module-map)

Next, under src, create components. Under components, create folder Hook.

Create index.js. Let’s create functional component called HookMqtt.
We create state hooks for our client, isSubscribed, payload, and connection status

HookMqtt

src/components/Hook/index.js

We declare a function where we use mqtt.connect for host and mqttOption. The reason why we do it here is because we need to update our client.

src/components/Hook/index.js

Notice setClient. When we connect, we update client with setClient, then the client variable can be used else where in HookMqtt functional component.

HookMqtt renders a UI like so:

Notice that it has four components:

  • Connection
  • Subscriber
  • Publisher
  • Receiver

Let’s talk about Connection first, as it is a component we need to be implemented to connect to our broker. Notice that Connect takes in prop mattConnect.

Connection

We want to pass in our previously created mqttConnect function into our connect prop parameter.

We will use this connect function to connect. However, let’s initialize url and options first.
First, in this class, we have a form, which initializes it via record.

src/components/Hook/Connection.js

We also have a record that has the basic connection properties of host, clientId, and port.
This is to connect to our free broker.

Next, we implement onFinish, which is a handler for when the user have filled out the form with user name and password.
We extract our connection information in order to form a url.

src/components/Hook/Connection.js

Options

We then create options object, which tells the broker what we want as far as the connection goes. Pay attention to clean and retain.

Clean property removes pending messages.

clean property means that we want to clean the session when we go offline. When this happens, then whatever pending QoS 1 and 2 messages that was published by other clients will not be there anymore.

We want to set clean to false so that we DO NOT clean the session when we go offline. That way, it still receives published Qos 1 and 2 messages when we go offline. When we log back on, we will see the messages.

By default clean is set to true. This means that when clients disconnect, whatever message that is published when they are offline will not be received when they sign back on.

src/components/Class/Connection.js

Normally if someone publishes a message to a topic, and no one is subscribed to that topic the message is simply discarded by the broker.

However the publisher can tell the broker to keep the last message on that topic by setting the retained message flag to true.

This can be very useful, as for example, if you have sensor publishing its status only when changed e.g. Door sensor. What happens if a new subscriber subscribes to this status?

Without retained messages the subscriber would have to wait for the status to change before it received a message.

However with the retained flat turned on, any subscribed client(s) would be able to get the
last retained message (current state of the sensor).

What is important to understand is that only one message is retained per topic.

Also, the next message published on that topic replaces the last retained message for that topic.

moving on, we add properties for authentication to our options. This way, we have url/options all ready to connect.

so we set our athentication user info onto options and then pass everything into connect.

Since the connect function is passed in by Mqtt, it will run this line to connect and then set the client object.

src/components/Hook/index.js

Back to HookMqtt. Now that we have a valid client to work with, let’s implement useEffect for when our client has changed to a new client.

When a new client comes onboard we have to make sure to get events so we can update our state when these happen:

src/components/Hook/index.js

  • connect status (connectStatus)
  • error status
  • reconnect status (connectStatus)
  • message status (payload)

We get the event updates via callbacks:

src/components/Hook/index.js

Now, when a client signs on, we can update our state payload and connectStatus when an event happens for that particular user.

Similar to how Connection is implemented, we’ll do the same for Publisher.

So in our functional component HookMqtt:

where mqttSub is:

It takes a subscription with the topic and qos data.
Now, where does topic come from?

In the Subscriber form, we have intiialValues with the record data:

where record data is:

topic and qos (in the Form) matches up to the ui controls. topic to textfield. qos to a pulldown. The options for the pulldown is dictated by qsOptioins.Provider, which gives us constant value context.

So that setups topic and qos defaults. If you use the pull down to select new qos, or type in new topic, the values parameter will be updated in onFinish.

Subscriber takes in prop sub and we call sub with our values. aka calling mqttSub.

In mqttSub, we see that:

it takes in a string topic, an options qos, and a callback for error anonymous function.

In client.d.ts, it is declared like so:

where IClientSubscribeOptions is defined as:

We need to put the qos to know what agreement is used between sender and receiver on the guarantee of delivering a message.

There are three levels.

  • 0 – client publish message, no acknowledgement from broker
  • 1 – sending is guaranteed. Broker will acknowledge. Client will re-send until it gets the broker’s acknowledgement
  • 2 – Sequence of 4 messages between sender and receiver (a kind of handshake) to confirm that message has been sent, and acknowledgement has been received. Both sender and receiver are sure that the message was sent exactly once.

Thus, client.subscribe will simply subscribe this client to the broker. And the broker will publish messages to this client in the future.

Receiving the Messages

Now looks at functional component Receiver.

In HookMqtt, it gives the state payload as prop into Receiver component.

and it updates the payload in useEffect:

The broker will be able to send messages to our client through the message event. Then we quickly update our payload.

In functional component Receiver, we append this new payload into our message queue.

where we render a List using this messages array:

Publishing Messages

In HookMqtt,

where

So following the interface defined for us, we give it a topic, a payload message, and options of type IClientPublishOptions where we set retain to true.

As mentioned earlier, retain to true means the user will get the last message. If we were to set this to false, then they will not.