teleren/devto huggingface dataset:
Different ways of calling a function in a React class
Tags: javascript, webdev, react
Published: 2020-07-27 05:01:47

Let's take a look at this class.

``` javascript
class Clock extends React.Component {
    constructor(props) {
        super(props);

        this.state = {date: new Date()};
    }

    componentDidMount() {
        this.timer = setInterval(() => (this.tick()), 1000);
    }

    tick() {
        this.setState({date: new Date()});
    }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    render() {
        return(
            <div>
                <h1>Clock</h1>
                <h1>It is {this.state.date.toLocaleTimeString()}.</h1>
            </div>
        );
    }
}

ReactDOM.render(<Clock />, document.getElementById('root'));
```

As you can see, this is a `<Clock />` class.

## First Question: ##
```javascript
this.timer = setInterval(() => (this.tick()), 1000);
```
Why does this work instead of, say:
```javascript
this.timer = setInterval(this.tick(), 1000);
```

The first one sets a **function as a callback** to the first argument of `setInterval` and actually calls the function in the callback.

The second invokes the function **on load**.

## Second Question: ##

Let's say I want to put the code as:

```javascript
this.timer = setInterval(this.tick, 1000);
```

Can you? Yes, you can.

You would have to bind the function in the constructor.

``` javascript
constructor(props) {
        super(props);

        this.state = {date: new Date()};

        this.tick = this.tick.bind(this)
    }
```

Why? Well, you actually have to call the function and that is what binding does behind the scenes.

However, if you don't want to explicitly `bind` the function, you can declare it using the ES6 arrow syntax.

```javascript
tick = () => {
    this.setState({date: new Date()});
}
```

This achieves the same effect of binding.

Thus, you can still do this, without having to explicitly `bind` the function.

```javascript
this.timer = setInterval(this.tick, 1000);
```

If you want to know more about binding, I will refer you to this very [comprehensive guide on binding](https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/). It got technical pretty fast for me, so take your time.

If you're wondering how I found it, I was looking through the [React website](https://reactjs.org/docs/faq-functions.html) and found the link.

I hope it helps you!
what's the difference between () => {} and () => ()
Tags: javascript, react, webdev
Published: 2020-07-27 04:42:30


Hey there, I'm going to be honest. This is a post that I will make for myself for reference. I've just started learning React and I got a little confused. 

So, what's the difference between `() => {}` and `() => ()`. I asked around and this was what I got.

`() => {}` is this:
``` javascript
() => {
   return something
}
```

`() => ()` is the same but **without** the explicit `return` statement:
``` javascript
() => (
   something
)
```
It is mostly a one-line return statement. So it essentially comes down to a simplified version, which is:

``` javascript
() => return something
```

Or you can just do 

``` javascript
() => something
```

There is also another form where you return a component.

``` javascript
() => <Component />
```

However, can you do this?

``` javascript
() => (
   var i = 0
   var a = i + 1 
   return a
)
```

This concludes to this:

``` javascript
() => (
   return var i = 0var a = i + 1 return a
)
```

While that is wrong, you can do this.

``` javascript
() => (
   return(
	<div>
		<p></p>
	</div>
   )
)
```

If you still feel slightly wonky about this, it is better to resolve to `() => {}` this first.

Feel free to correct me if I'm wrong ya!
Different Array Methods (cont.)
Published: 2020-07-27 04:01:39

Here are a few more array methods that will useful as you learn javascript!

### Array.concat() 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/raw0d8y0o00i9xl4y9vc.png)

##### What it does: 
The concat method will create a new array by adding the values from the array that was passed in as an argument(numsToo) to the end of the original array.

##### What it returns: 
This returns a brand new array. The two array that were combined remain the same. You'll see at the bottom, that nums returns its original values.

### Array.indexOf() 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zpz4uln0to0ue0jny8ti.png)

##### What it does: 
The indexOf will take an argument (string, integer, etc) and find the first instance of that in the array.

##### What it returns: 
This will return the index of the first instance of the value that was found. In this instance, we are looking for the number 3 and it is first found at the 2nd index. 


### Array.reverse() 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vrpijan1w7va4enqvql5.png)

##### What it does: 
The reverse method will take an array and reverse it. 

##### What it returns: 
Not only will this return a return the array reversed, but the array will be modified and reversed. You can see at the bottom when we call nums again, it is still reversed.

### Array.join() 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5998bjxyke1s301y01bv.png)

##### What it does: 
The join method will do basically what it says. It will join the indexes in the array with what is passed in as an argument. By default it will join the items by a comma.

##### What it returns: 
This will return a string of the joined array. Keep in mind that the join method will not modify the original array.
Converting a Preact Component to use hooks with Sophia Li
Tags: learninpublic, pairprogramming, javascript, react
Published: 2020-07-27 04:01:08

A few weeks ago, I wrote a post asking DEV community members if they wanted to potentially pair program with me during a live coding session.

{%link https://dev.to/devteam/let-s-pair-during-a-live-coding-session-8he %}

A lot of interest was generated and so we did our first live coding pairing session that was streamed on [doingdevfordev.com](https://doingdevfordev.com). It was with DEV community member [Sophia Li](https://twitter.com/sophia_wyl).

She worked on the `<ImageUploader />` Preact component in the DEV/forem codebase. It was originally a class component that she converted to a function component using the [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook.

For the full recording of the pairing session check out the YouTube video below. Also, feel free to subscribe to [my channel](https://m.youtube.com/channel/UCBLlEq0co24VFJIMEHNcPOQ). 😉

{%youtube gy2LyxQtlSQ %}

Near the end of the pairing session we discussed the possibility of using the [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer) hook instead. After the pairing session, Sophia continued working on the PR she created and implemented the necessary changes to use the `useReducer` hook.

For those interested, here is the merged PR.

{%github https://github.com/forem/forem/pull/9369 %}

It was awesome pairing with Sophia and by the way, she’s looking for her next role!

{%twitter 1273775174718943232 %}

Looking forward to the next pairing session!
Live Component Preview for React
Tags: tutorial, javascript
Published: 2020-07-27 04:00:59

---
title: Live Component Preview for React
published: true
description:
tags: #tutorial #javascript
---

Previously on stupid mini tools, we built [Hen](https://hen.reaper.im) and if you were one of the people who went through the source code and commits, You might have noticed that I tried 2 approaches to get the preview working.

1. Created an in-code sandbox and run the component there
2. Created an iframe and gave it access to all the resources it needed.

Now obviously the Iframe way is a lot more simpler and easier to go about and creates a perfect sandbox where the code inside doesn't impact the whole application.

But I did that because I had to publicly let hen be used. 
And had the assumption that other providers of the Live playground, like [BaseWeb](https://baseweb.design/) or [Vercel's Geist Design](http://vercel.com/design) were also setting up iframe's for the previews but much to my surprise they had the in-code sandbox.

So, I started thinking about it again and instead of messing with the original code of hen, I started a experimental project where I'd test the security vulnerabilities of this approach and try to fix/block them as much as I can.

We'll go through the base of the approach on how you should be going through to create an in-code code sandbox. This is specific to react but you can obviously extend and modify as needed. I'm only going to layout the Algorithm for you and you can go ahead from there. As for people who really need to check for the source code, you can head over to the github link at the end. 

### Algorithm
1. Transform JS/JSX to JS and Parse an AST
2. Get hold of the React Node and Convert it back to JS.
3. Create a wrapper component of the react node
4. Pass down package dependencies 
5. Render it into a container.


Let me go through the points in a little more detail. 

1. You take in the code and now convert it into an AST using something like `acorn`, an AST or Abstract Syntax Tree is a structure of the source code in a tree format. Basically, it creates a nested object of objects and array that represent the code you provide it with and then you can use that information or tree to covert the input to other languages etc. In our case, this is the react code that we type and it's compiled into `React.createElement` using Babel(@babel/standalone) in the browser and then we pass it to acorn to get the AST.

2. We browse through this AST to pull out only the React node
3. Then create a wrapper for it but before creating the wrapper we use something like `escodegen` to regenerate the JS code from the AST node.

4. The above generated string is passed to `new Function([args],generateCode)` to give us a function with the component definition.

5. We basically store the above component generation code into a variable and then render it onto the dom like any other React component

Now if all of that went above your head and going through the source code would help you better. 

[Source Code](https://github.com/barelyhuman/hen-experimental)
[Experimental Approach Demo](http://beta.hen.reaper.im/)
Advanced Web Design and Dev concepts and tricks (help!)
Tags: webdev, gsap, barbs, awwwards
Published: 2020-07-27 03:43:46

---
title: Advanced Web Design and Dev concepts and tricks (help!)
published: true
description: How to reverse engineer and use advanced web design and development concepts. 
tags: webdev, gsap, barbs, awwwards
//cover_image: https://direct_url_to_image.jpg
---

#### Hi, I'm on a journey to collect all the 5 Web Design feature stones to gain enough power to one day have a project listed on awwwards.com.
I've also come to you, a humble developer... asking for help.


There's a huge gap between learning animation and page transition libraries like GSAP and BarbaJS and building come of the cool stuff showcased on awwwards.com. Stuff like interactive cursors are simple enough but even though there's nowhere I can find online for how to actually implement it in the way it's commonly used (trade secret among agencies maybe?).

However, what's pressing on my mind right now is a much more complicated one. The best way I can describe it is "persisting an element between pages" when using page transition libraries like BarbaJS. 
Actually, let me just show you: [https://danielebuffa.me/work](https://danielebuffa.me/work). Just click on the portfolio item there and it takes the current page's image and _(get ready to nut)_ it transitions it into the next page. 

![Surprised](https://dev-to-uploads.s3.amazonaws.com/i/a2j3zsaohfwfunu0ffsg.gif)

This is the stuff of legends. 

#### And... I can't quite figure it out.
So I'm asking the old masters in the community here to help me reverse engineer it and explain the implementation a bit. 

------------------

What are your favourite hot web design and dev tricks and concepts that make your friends wonder if you have a website fetish? I'd love to discuss. 

![Wink](https://dev-to-uploads.s3.amazonaws.com/i/6dn8v60001zkqgfkvwuk.gif)
Windows 10 Virtual Desktops
Tags: productivity
Published: 2020-07-27 03:41:08

I'd like to recommend a feature of Windows 10 (that might be present in previous versions, I'm not sure), that I know it exists, but never gave a thought on how it could be useful: Multiple Virtual Desktops. You can divide your opened applications and windows in different virtual desktops, to help organize your work. 

To create a new desktop, just press Ctrl + Windows + D, or press Windows + Tab and click "New Desktop": ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m1biaait5cjh0wozh9g6.png)

You can switch between Desktops with Ctrl + Windows + [Right Arrow] and Ctrl + Windows + [Left Arrow], or by pressing Windows+Tab and clicking on the desktop. 

Now, when you open an app, it will remain in the desktop you opened it, unless you press Window+Tab, right click on the window listed, Move To..

I've thought about two scenarios that this feature could be usefull. You could have a desktop only for development related programs, visual studio, sql server, browser for searching and testing etc. In another desktop you can keep non development related apps, like Media Players, messengers etc.

Another nice scenario: Imagine you're working on a PHP Project, with Visual Studio Code, My Sql, along with some browser tabs to run your project and some searches about that. Suddenly, you get a call about another project, and have halt your currently work to solve a bug on it. But this is a C# project , so you open a new desktop, and open Visual Studio , SQL Server and browsers, to work on this new project, without having the other windows there to clutter your desktop. When you need to change to the previous project, just switch back the previous desktop.
Tiny Invisible Machines
Published: 2020-11-01 08:00:57

---
title: Tiny Invisible Machines
published: true
date: 2020-07-27 03:39:54 UTC
tags: 
canonical_url: 
---

At this exact moment on Earth, nature’s symphony is accompanied by the persistent hum of billions of tiny machines we have embedded into reality. These machines are dictated by the slightest variance in electrical impulses and power the world economy, yet only a small subset of us are privileged enough to ponder the implications of such invisible architecture. Fewer still have the magical combination of ability, power, and luck required to influence the design and implementation of these systems which will govern _all_ of our lives. That is why as software developers, we have an urgent responsibility to build _strictly and solely_ systems which respect the rights of its users, to educate our peers in other disciplines about the systems and their common pitfalls, and to demand public ownership of essential infrastructure.

You are likely not aware that the software you interact with is imbued with ulterior motives. How can a bunch of words and buttons on a screen _disrespect_ you? Thanks to the cunning legal teams behind major commercial software companies, the apps you run on your phone, tablet, and computer are allowed to perform egregious violations of your privacy while you watch your friends’ social broadcasts. And in the United States, thanks to a defanged regulatory body and increasing oligarchic control of the legislature, the companies which siphon the most data about your personal habits grow the fastest - thus incentivizing _all_ companies to adopt this strategy or die. The practice of collecting, processing, and analyzing users’ behavior to create digital shadows upon which advertising campaigns can modeled gives way to the absurdly high stock valuations which currently prop up our economy. By commodifying individuality, Big Tech has laid the groundwork for a marketplace of souls. How much are you worth?

Thankfully, a [free software movement](https://www.fsf.org/about/) exists to provide shelter from these exploitative platforms. Free software bestows “four freedoms” onto its users:

- (freedom 0) the freedom to run the program as you wish, for any purpose
- (freedom 1) the freedom to study how the program works, and change it so it does your computing as you wish. Access to the source code is a precondition for this.
- (freedom 2) the freedom to redistribute copies so you can help your neighbor.
- (freedom 3) the freedom to distribute copies of your modified versions to others. By doing this you can give the whole community a chance to benefit from your changes. Access to the source code is a precondition for this.

When software is licensed according to these ideals, users can interrogate the electrons transporting their personal data, decide whether the functionality the software offers is worth the extraction, and sidestep the data → information → knowledge pipeline feeding into the surveillance software sludge factory.
Get geolocation from browser with HTML5 and JS
Tags: javascript, html
Published: 2020-07-27 03:38:32

The code:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Handling Geolocation Errors</title>
<script>
    // Set up global variable
    var result;
    
    function showPosition() {
        // Store the element where the page displays the result
        result = document.getElementById("result");
        
        // If geolocation is available, try to get the visitor's position
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
            result.innerHTML = "Getting the position information...";
        } else {
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    };
    
    // Define callback function for successful attempt
    function successCallback(position) {
        result.innerHTML = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
    }
    
    // Define callback function for failed attempt
    function errorCallback(error) {
        if(error.code == 1) {
            result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
        } else if(error.code == 2) {
            result.innerHTML = "The network is down or the positioning service can't be reached.";
        } else if(error.code == 3) {
            result.innerHTML = "The attempt timed out before it could get the location data.";
        } else {
            result.innerHTML = "Geolocation failed due to unknown error.";
        }
    }
</script>
</head>
<body>
    <div id="result">
        <!--Position information will be inserted here-->
    </div>
    <button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>
```
DotNetCore Native Network Framework Sockety
Tags: dotnet, socket
Published: 2020-07-27 03:31:44

[Japanese Document](README-ja.md)
# Sockety
It is a network framework written in .NET Core.
It wraps Socket and allows for easy server-client communication.
## Communication Method.
When a client connects to a server in Sockety, it connects TCP and UDP.
## Function.
Disconnection detection (internal use)
Client to server communication (with return value from server)
Server to client push communication
Lightweight communication using UDP
Encrypted communication using SSL (TCP only)
UDP communication using AES
Authentication at the time of communication using an authentication token
It is.
[UDP avoids NAT with HolePunching](https://qiita.com/k-yamamoto/items/1bc295f83c873921b408)

# Development History
Net Core, which requires multi-platform communication, and MagicOnion is used for this purpose.
MagicOnion uses gRPC for its communication core and uses native code. 
It's not really necessary to run on Windows ARM, but it's for Hololens2.

# QuickStart
server-side

```
int PortNumber = 11000;
//SSL Setting
var serverSetting = new ServerSetting { UseSSL = true }
serverSetting.LoadCertificateFile("++++.pfx", "certPassword");

//Authentication Filter.
var authtificationFilter = new LocalAuthentificationFilter();
serverCore.SocketyFilters.Add(authtificationFilter);

Add(authtificationFilter); //UDP Port Setting
serverCore.InitUDP(11000, 11120);
//Sockety Start
serverCore.Start(localEndPoint: new IPEndPoint(IPAddress.Any, PortNumber);, _stoppingCts: _stoppingCts, parent: this, _serverSetting: serverSetting);
```

```
Client.Connect("localhost",11000, "MyApp",this);
```


Client (calling party) TCP

```
client.Send("Join", Encoding.ASCII.GetBytes($"{DateTime.Now.ToString()}"));
```
you can call a method on the server (in this case, Join) and pass in the current time as an argument.

Server (the one being called) TCP

```
public byte[] Join(ClientInfo sendclientInfo,byte[] JoinDate)
```
The receiving end of the server looks like this
ClientInfo→Source client information
JoinDate→client.Send's second argument

Client (calling party) UDP

```
client.UdpSend(Encoding.ASCII.GetBytes(DateTime.Now.ToString()));
```
Server (the called party) UDP
```
public void UdpReceive(ClientInfo sender, byte[] obj)
{
    //Broadcasting client data to all clients
    serverCore.BroadCastUDPNoReturn(sender, obj);

    string str = Encoding.ASCII.GetString(obj);
}
```

# Package.

```
dotnet add package Sockety
```
Get it at


# Usage.
I will describe the details of how to use it later, but please refer to the Example first.
Sockety (body)
Example/SocketyServer (sample server)
Example/SocketyClient (sample client)
Example/SocketyClientUWP (sample client version)

# Repositoty
[Github](https://github.com/kyamamoto03/Sockety)
[Nuget](https://www.nuget.org/packages/Sockety/)