teleren/devto huggingface dataset:
When to use Class Component and Function Component??
Tags: react, javascript
Published: 2021-05-09 18:37:17

### Hello Everyone,

In this post let's understand where to use the Class Component and Functional Component in react

Before diving, Let's start understanding what is a component in react?

### Component

Websites or Web Applications developed using react is the combination and interlinking of different Components.

Components let you develop the UI of the website independently and even we can use reusable components to implement a similar UI.

React facilitates the developer with **Class Component** and **Functional Components**

### Class Components

Class Components are built using [ES6 Class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)


```
class Welcome extends React.Component {
  render() {
    return <h1>Super Excited to post my first post in Dev Community</h1>;
  }
}
```


### Functional Component

The simplest way to write the Component in react is to write a JavaScript function


``` 
function welcome(props) {

 return <h1>Super Excited to post my first post in Dev Community</h1>;

}
```

We can use the Arrow Functions as well for the functional Components

```
const welcome = (props) => <h1>Super Excited to post my first post in Dev Community</h1>;
```

Hope we had a short and good recap about the Class and Functional Components

The above two components which are written in class and Functional Components are equivalent from React’s point of view.

Now the major question rises in your developer's mind!

# When to use the Class Component and the Functional Component??

To answer this question we need to have a decent understanding of the state of the component.

To recall or revise the concept of the `state` of the component, I suggest you refer to [this](https://reactjs.org/docs/state-and-lifecycle.html#gatsby-focus-wrapper).

In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props.

Whenever we have the use case with the State of the component and rendering the UI based on the Component State, use the **Class Components**

**Class Components** should be preferred whenever we have the requirement with the **state** of the component.

In the beginner stage of the developer journey, we should be familiar with the **Class Components** and the **Functional Components**, As we progress towards the Advanced stage of our developer journey, We are able to understand much more cool stuff provided by React like **Hooks**

In React version > 16.8, React even facilitates developers with **Hooks** to use the **state** and other React features even without writing the **Class Component** 

To know more about **Hooks**, Refer to [this](https://reactjs.org/docs/hooks-intro.html)

I love to appreciate your enthusiasm to learn more.

Thanks for Reading!

### I'm Phani Murari

[Instagram](https://www.instagram.com/im_phani_murari/)
[LinkedIn](https://www.linkedin.com/in/phanimurari/)

#CodeIsPeace
Unfollow - Animated Short Film | Ravik Studio
Published: 2021-05-09 18:17:36

Unfollow is a funny animated moral story by Rahul Singha.

**Rate:** https://imdb.com/title/tt13074804/

### About the Story:
On a beautiful evening at a beach, a man was lying on a chair and enjoying the sunset. Suddenly he saw an unidentified flying object (U.F.O) appears in the sky.

The man amazed by the incident and just because he is a social media addicted person, he’s trying to take a snap of the object for likes, for fame, for money.

The object is floating all over the sky and the man wants to reach the position to take the photo. The unknown species got irritated by the human and shot him with his alien gun and disappeared into the sky.

#### The moral in the story is:
Don't follow unknown things or persons to fulfil your addiction or desire.

--- + ---

*Written and Directed by Rahul Singha
In Association with [Don Ka Adda](https://www.youtube.com/DonKaAdda)
Produced by [Souvik Paul](https://www.instagram.com/amisouvikpaul) & [Rahul Singha](https://www.instagram.com/donrahul_89/)
Copyright: [Ravik Studio](https://www.youtube.com/channel/UCcYHCGujld8Fe3P8sc4qTYQ)
Motion Capture - [Souvik Singha](https://www.imdb.com/name/nm11890940)*

--- + ---

Backgrounds, Editing, Art Direction and Character Design, Concept Art and Production Design, Coloring and Shading, Voice - Rahul Singha

VFX & Sound Mixing - Rahul Singha, Souvik Paul
Animation Studio - Ravik Studio (Souvik Paul, Rahul Singha)
Special thanks to Souvik Paul
First App on React
Tags: reactnative, sampleapp
Published: 2021-05-09 18:13:01

Just completed React crash course by Brad Traversy (https://www.youtube.com/watch?v=w7ejDZ8SWv8) with code along, picked up a little about neumorphism design on the way. 
Comment your thoughts and what next should app should I make to learn more of react

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbtprnyc44uqw4wbtue0.JPG)![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h42ygo8qv6xivi39r29r.JPG)![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn3hdgfg3j9cr69gx0p1.JPG)
The pain of aggregations in MongoDB Compass
Tags: mongodb, aggregations, atlas, compass
Published: 2021-05-09 18:11:34

Why are aggregations so tough in MongoDB compass? It takes so much time to use the pipeline builder to create a multi-stage aggregation. I feel it is so much easier in Robo3t. It so less fancy and so much faster. Yet somehow all my [Fiverr](https://www.fiverr.com/vjnvisakh) clients use Compass. 

Recently I discovered you can write aggregations in the Shell part of Compass in case you want to see the output directly. Like below.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jmphrsfgyi7wmq2wnzz.png)

One of my clients taught me that I can export code to a specific language too from the Compass Export option like so. It supports Java, Python, Node, and C# as of now. 

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

I really hope they make the aggregation pipeline simpler.

Please do comment if there is an easier way of doing this. Would really help me out. 

Happy programming!
Make Icon Component
Tags: svelte, iconmonstr, svg, javascript
Published: 2021-05-07 17:09:07

When using an icon in a web framework, a predefined component is used like `fontawesome`. But if you have just a few icons or want to use a custom icon, I will show you how to make your own component with SVG.

For SVG, I get from https://iconmonstr.com/ which is a very cool icons have.

```js
<script lang="ts">
/* eslint-disable no-unused-vars */

enum IconTypes {
  plus = "M24 9h-9v-9h-6v9h-9v6h9v9h6v-9h9z",
  arrow = "M8.122 24l-4.122-4 8-8-8-8 4.122-4 11.878 12z",
}
type IconTypesString = keyof typeof IconTypes;

type PosTypes = "left" | "down" | "up" | undefined;

export let icon: IconTypesString;

export let height = "24";
export let width = "24";

export let className: string = undefined;
export let position: PosTypes = undefined;

const totalClass = [className, position].join(" ");
</script>

<svg xmlns="http://www.w3.org/2000/svg"
  class={totalClass ? totalClass : undefined}
  width="{width}"
  height="{height}"
  viewBox="0 0 24 24">
  <path d={IconTypes[icon]}/>
</svg>

<style lang="scss">
  .left {
    transform: rotate(180deg);
  }

  .down {
    transform: rotate(90deg);
  }

  .up {
    transform: rotate(-90deg);
  }
</style>
```

Added an enumerate to list of icons as type so when we using this component, it will help autocomplete.
Transformation CSS variable using for not repeating icons also added custom `className` props to control your icon in CSS part.
I fixed viewBox to `0 0 24 24` so __width__ and __height__ can works. But if your SVG is different than 24-24 you should update `viewBox` after that you can change value with __width__ and __height__.

That's all welcome your new icon component.

```html
<Icon icon="arrow" className="arrow" position="left"/>
```
If you need to middle of the content just wrap with `flex` use `align-items` center.
upload image file into a HasMany relation model
Tags: laravel, php
Published: 2021-05-09 18:01:38

hello i am using laravel 8, i have a product and image table and i want to be able to upload 3 images with each product

**product model***
```php
class Product extends Model implements Auditable
{
    use HasFactory, AuditableTrait;

    const FILLABLE = ['name','price','description'];
    protected $fillable = ['name','price','description'];
    
    public function images()
    {
        return $this->hasMany(Image::class, 'id');
    }
}
```
**product migration**
```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->double('price');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
```
**image model**
```php
class Image extends Model
{
    use HasFactory;

    protected $fillable = ['product_id', 'file_path'];

}
```
**image migration**
```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_id')->constrained();
            $table->string('file_path');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}
```
and this the methode inside my product controller that supposed to store data 
```php
public function store(Request $request)
    {
        $product = Product::create($request->only('name','price','description'));
        if($images = $request->file('images')){
            foreach($images as $image){
                $image->store('product','public');
                Image::create([
                    'product_id' => $product->id,
                    'file_path' => $image->hashName()
                ]); 
            }
        }
        return $product;
    }
```
when i test this method with postman i was able to store data into product 
but the image table stays empty it did not receive any data
any help please!
What's the last project you contributed to?
Tags: watercooler, github, opensource
Published: 2021-05-09 17:47:14

---
title: What's the last project you contributed to?
published: true
description: 
tags: watercooler, github, opensource
cover_image: https://fossbytes.com/wp-content/uploads/2018/07/github-learning-lab-768x432.png
---
Excluding your own projects, could you please share the last open-source project that you contributed to?

Exciting to discover some new, awesome repositories.
Have you invested in crypto and did it pay off?
Tags: watercooler, crypto
Published: 2021-05-09 17:38:47

---
title: Have you invested in crypto and did it pay off?
published: true
description: 
tags: watercooler, crypto
cover_image: https://www.financemagnates.com/wp-content/uploads/2021/03/DogeCoin-header-min.jpg
---
Cryptocurrency is a digital currency that can be used to buy goods and services but uses an online ledger with strong cryptography to secure online transactions.

According to [CoinMarketCap](https://coinmarketcap.com/), more than 6,700 different cryptocurrencies are traded publicly and the total value of all cryptocurrencies is more than $2.2 trillion.

Have you invested in crypto and did it pay off?
how to automate your workstation setup
Published: 2021-05-09 17:38:36

Automate the workstation setup to make everything works at day one. Migrate to a new device fast. Make it easy to follow your standard within a company. Improve security by reviewing what you install. 

## background

[pivotal](https://github.com/pivotal/workstation-setup) uses a script to setup their machines. [Zalando](https://engineering.zalando.com/posts/2021/01/creating-a-uniform-landscape-for-mac-software.html) uses JAMF to manage devices. I also made good experiences with *workspace one intelligence hub*. 

## requirements

The user selects different roles e.g., design vs programmer / work vs private. The script runs on mac. The script can setup the dotfiles, system configurations, binaries and the app store. The setup makes the preferred behavior easy but people can extend it.

## solution

Use a [bash script](https://github.com/dennisseidel/setup-your-mac-template) that includes the default setup. Prevent manual installation through device management. Allow the employees to create pull request to the script to add software. Review the pull request and then make them available to everyone. 

## alternatives

* In lower risk environments go for an "*add software by yourself and it gets pushed to your device and we only verify it later"*.
Set up Cypress in your React Project
Tags: beginners, testing, react
Published: 2021-05-09 17:13:16

1. `npm install -D cypress` => install Cypress as dev dependency
2. You can create a script in package.json to open cypress: 

```
"scripts": {
     "cy:open": "cypress open"
}
```
3. `npm run cy:open` => starts the cypress test runner
4. You can create a script in package.json to run Cypress tests in the terminal (so you can, for instance, run it in continuous integration):

```
"scripts": {
     "cy:run": "cypress run --spec \"cypress/integration/app/**/*\""
}
```

^ you will have to create a `app` folder inside `cypress/integration`, a good place to keep your tests.
Performant Pagination Technique for SQL databases
Tags: sql, pagination, performance, optimization
Published: 2021-05-09 17:10:37

In this article, I will go over a performant technique for paginating records. 

The most common way of implementing pagination is by using `offset based pagination`. But this is not really performant technique when dealing with huge dataset. 

Let's say we need to write a query to fetch latest posts for a social media website. 

SQL query would look like this: 

`SELECT * FROM POSTS ORDER BY ID DESC OFFSET 0 LIMIT 10`

Let's say you want to select next page for `page 2` you will change offset to `10` & for `page 3` offset will be `20` as mentioned below:

`SELECT * FROM POSTS ORDER BY ID DESC OFFSET 10 LIMIT 20`

`SELECT * FROM POSTS ORDER BY ID DESC OFFSET 20 LIMIT 30`

This technique selects all the records then skips records. And for that reason it is not really a performant technique. Consider a scenario where you are skipping million rows in order to fetch the next 10 records. 

But there is a way, we can improve on this:

`SELECT * FROM WHERE POSTS ID < {MAX_POST_ID+1} ORDER BY ID DESC LIMIT 10`

This query would only select all the records that need to be returned & hence this would be much faster. Also since `ID` is an `index` so search over it would be much faster. 

For first page, data returned would look like this.

######ID  BODY
20  Post Body
19  Post Body
18  Post Body
17  Post Body
16  Post Body
15  Post Body
14  Post Body
13  Post Body
12  Post Body
11  Post Body

And to fetch next 10 records(and subsequent queries) you would pass `11` as `post_id`. So query would look like this:

`SELECT * FROM POSTS 
WHERE ID < {POST_ID}
ORDER BY ID DESC LIMIT 10`

######ID  BODY
10  Post Body
09  Post Body
08  Post Body
07  Post Body
06  Post Body
05  Post Body
04  Post Body
03  Post Body
02  Post Body
01  Post Body

So basically to fetch next page all you have to do is to pass `post_id` of last record returned from previous query. 

This kind of pagination is not length aware. Cause again if we go on to calculate length then it would slow down the API call & subsequently apps will take longer to load newsfeed.
List of 404 on Parastate
Published: 2021-05-09 17:08:31

##1 - https://github.com/ParaState/pallet-ssvm

The link Substrate on this page as shown in screenshot shows 404

![Screenshot 2021-05-09 at 18.05.08](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/va1samkg6h69s5lhw32a.png)

![Screenshot 2021-05-09 at 18.06.11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsc55lnukznnjd9g45jk.png)

##2 - https://medium.com/ethereum-on-steroids/an-improved-paper-with-go-to-market-strategies-471e45c42dbb

In this article the white paper is no longer accessible.

https://www.parastate.io/assets/wp.pdf

![Screenshot 2021-05-09 at 20.03.07](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ix76n26byalmhzdr6ob5.png)
 
![Screenshot 2021-05-09 at 20.05.29](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jkly9ry74l7nmbcv66t.png)
HostListener how to use
Tags: angular, decorators, hostlistener
Published: 2021-05-09 17:08:28

Hi, today I will explain how to use the <strong>HostListener</strong> decorator easily.

First, this decorator we use for:
<em>This decorator is listening for a specific event by the host element<em>

Go to the code example:
<em>Each time you click inside the component, the counter will increase by 1</em>

```typescript
  @HostListener("click", ["$event"])
  onClickEvent(event: Event) {
    this.clicksCounts += 1;
  }
```

{% codesandbox romantic-kilby-46515 %}

If you want to know all the events that you can play with HostListener you can see it in <strong>w3school</strong>  list here ->[https://www.w3schools.com/jsref/dom_obj_event.asp]
Running k3s inside WSL2 on a Surface Pro X
Tags: k3s, wsl2, surfaceprox, kubernetes
Published: 2021-05-22 10:31:26

---
title: Running k3s inside WSL2 on a Surface Pro X
published: true
date: 2021-05-09 17:00:00 UTC
tags: k3s, wsl2, surfaceprox, kubernetes
canonical_url: https://carlos.mendible.com/2021/05/09/running-k3s-inside-wsl2-on-a-surface-pro-x/
---

I’m a proud owner of a Surafe Pro X SQ2 which is an ARM64 device. If you’ve been reading me, you know I like to tinker with kubernetes and therefore I needed a solution for this device.

I remembered reading about [k3s](https://k3s.io/) a lightweight kubernetes distro built for IoT & Edge computing, and decided to give it a try.

## Installing k3s in WSL2

### Download the binaries

```
wget https://github.com/k3s-io/k3s/releases/download/v1.19.10%2Bk3s1/k3s-arm64
```

### Rename the file

```
mv k3s-arm64 k3s
```

### Make the file executable

```
chmod +x k3s
```

### Move the file to `/usr/local/bin`

```
sudo mv k3s /usr/local/bin
```

### Copy to k3s config file to `$HOME/.kube`

```
sudo cp /etc/rancher/k3s/k3s.yaml $HOME/.kube
```

### Make current user owner of the k3s config file

```
sudo chown $USER $HOME/.kube/k3s.yaml
```

## Running k3s

### Run the k3s kubernetes server

```
sudo k3s server
```

## Test k3s

From another WSL2 console window:

### Add the k3s config file to KUBECONFIG environment variable

```
export KUBECONFIG=$HOME/.kube/config:$HOME/.kube/k3s.yaml
```

### Use k3s context

```
kubectl config use-context default
```

### Check all running pods

```
kubectl get po --all-namespaces
```

you should get an output similar to this one:

```
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system helm-install-traefik-mhhfz 0/1 Completed 0 20d
kube-system metrics-server-7b4f8b595-7cfsb 1/1 Running 1 20d
kube-system svclb-traefik-pqn56 2/2 Running 2 20d
kube-system coredns-66c464876b-pnpgm 1/1 Running 1 20d
kube-system local-path-provisioner-7ff9579c6-nhnbj 1/1 Running 6 20d
kube-system traefik-5dd496474-94lt5 1/1 Running 1 20d
```

> Note: k3s uses: **local-path-provisioner** and saves volume data in the **/var/lib/rancher/k3s/data** folder

Hope it helps!!!
Add Bootstrap and FontAwesome to your Ruby on Rails 6 application
Published: 2021-05-09 16:43:39

#Bootstrap

We will use yarn to add Bootstrap and it's dependencies - jquery and popper.js

Make sure you have yarn installed then run the following command on the terminal in the root directory
`yarn add bootstrap@4.3.1 jquery popper.js`

We can check that the libraries have been installed successfully by checking the package.json file.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u44bbek12hmfezltdywo.png)


Now let's replace the config/webpack/environment.js code with the following:

```
const { environment } = require('@rails/webpacker')

const webpack = require("webpack")

environment.plugins.append("Provide", new webpack.ProvidePlugin({

$: 'jquery',

jQuery: 'jquery',

Popper: ['popper.js', 'default']

}))

module.exports = environment
```
We added this code so the application's javascript understands jquery and popper.js syntax.

Now we have to import bootstrap and to do that we will go to app/javascript/packs/application.js and add the following line:
```
import "bootstrap" 
```
And That's it for javascript.

Now the CSS
Let's Go to app/assets/stylesheets/application.css and add the following above the require_tree and require_self lines:
```
*= require bootstrap
```
So it would be like this
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y67hrsf05qpcnkvv2zsr.png)

Now let's add some custom styles to the app styling, so we will create a new file  (app/assets/stylesheets/custom.css.scss).

Here we import the bootstrap library first so we  are able to modify styles for not just the new classes but existing bootstrap classes as well:
```
@import 'bootstrap/dist/css/bootstrap';
```

That's it! now we are good to go with bootstrap 4 in your Rails 6 application. 


#FontAwesome

Make sure you have yarn installed then run the following command on the terminal in the root directory
`yarn add @fortawesome/fontawesome-free`

We can check that the successful installation by checking the package.json file.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sktkybsm89chlave9vu.png)

Now we have to import font awesome and to do that we will go to app/javascript/packs/application.js and add the following lines, the js to make sure it works on production as well as development:
```
import "@fortawesome/fontawesome-free/js/all";
import "@fortawesome/fontawesome-free/css/all";

```
That's it for FontAeswome!

Now we have added bootstrap and font awesome successfully to our rails application.

Happy Coding!