teleren/devto huggingface dataset:
Switching from Vue to React
Tags: react, vue, webdev
Published: 2021-08-12 08:40:54

I recently decided to migrate a [Vuejs](https://vuejs.org/) Project to [React](https://reactjs.org/). I read many comparisons and it always seemed to come to Vuejs being the simpler of the 2.

"Use Vue for quick execution and small to medium projects and React for big projects."

"JSX sucks, Vuejs is simple and looks just like HTML."

For reading that, I assumed that react was a hard clunky framework so always stayed away. The issue was that React devs are abundant. Everyone knows react, not everyone knows Vue. Using react would be a better long term investment for the [app development company in Singapore](https://potado.co/app-development-singapore) where I work. My company [develops software](https://potado.co/software-development-singapore) for many large companies and startups, so learning react will be beneficial for my long term career as a developer. Working at a company is a much better experience than working as a freelance app developer. Hiring a mobile app development company in Vietnam is also a great option as some of the best programmers in the world are over there. [Developing software in Vietnam](https://potado.co/software-development-vietnam) is a popular choice for both local companies as well as companies in Singapore and Australia as Vietnam is in a similar timezone and the cost is much lower.

Anyway, my team and I decided we should switch to React and we were pleasantly surprised. After doing a bit of reading up (about 60 mins), we were ready to start coding. React is easy, really easy. But then we came across 2 way binding. In VueJs it is simply a matter of:

<text-field v-model="name"></text-field>

data: () => {
  return {
    name: ""
  }
}

In React:

constructor(props) {
    super(props)
    this.state = {value: ""}
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(event) {
    this.setState({value: event.target.value})
  }

  render() {
    return (
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    )
  }

So VueJS definitely does come with more magic out of the box but once you get the hang of React, it's much simpler, more like JavaScript. 

What do you think? I always read about VueJS being the better framework, so if you have used both and prefer React, I'd love to hear why.
Optimization: Finding the best solutions
Tags: beginners, algorithms
Published: 2021-08-12 10:40:08

Imagine how a swarm of bees find food sources. While visiting areas, different bees will find plants of different quality and quantity. Some might be better than others but they gravitate towards the best. Optimisation algorithms in AI work this way too.

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

Optimisation algorithms are used to evaluate massive search spaces for good solutions. Many of these algorithms are not guaranteed to find the absolute best solution; they attempt to find the global best while avoiding local best solutions.

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

A global best is the most optimal solution, and a local best is a solution that is less optimal. If the goal is to minimize, the smaller the value, the better - vice versa for maximization. The aim is to incrementally find local best solutions and converge on a global best one.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3vv668bhe5navtlukobi.jpg)

Parameters of the algorithm need careful attention. It must strive for diversity in solutions at the start and gradually gravitate toward better more homogenous solutions through each generation. Without divergence of solutions, a risk of getting stuck in a local best increases.

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

Genetic algorithms and swarm optimisation are fascinating and powerful, see Grokking AI Algorithms with Manning Publications: [http://bit.ly/gaia-book](http://bit.ly/gaia-book), consider following me - [@RishalHurbans](https://twitter.com/RishalHurbans), or join my mailing list for infrequent knowledge drops: [https://rhurbans.com/subscribe](http://bit.ly/gaia-book).
What is your opinion on Java web frameworks as compared to the JavaScript frameworks?
Tags: beginners, webdev, javascript, java
Published: 2021-08-12 10:31:59

Hey dev.to community,
I'm planning to start web development using either Java or JavaScript frameworks. I would like to know that with which language should I start learning considering the time it will required to getting started quickly. I'm already familiar with the Java language.
Thanks!
Create dummy objects for testing
Tags: php, testing, tdd
Published: 2021-08-12 10:30:38

When testing our application, we usually need to use our objects with fake data in order to cover as much as possible all combinations.

Here is where `Object Mother pattern` helps us.

## Use case

Imagine we have the following classes that we need for any of our tests:

```php
class UserName
{
	public function __construct(private string $value)
	{
	}

	public function value(): string
	{
		return $this->value;
	}
}

class User
{
	public function __construct(private UserName $name)
	{
	}

	public function name(): UserName
	{
		return $this->name;
	}
}
```

As you can see, there is an *entity class* called `User` which contains a *value object* called `UserName` corresponding to the `name` attribute.

Instead of forcing its values in a test (which will make it weak, because it tests the same data each time) we can use the pattern `Object Mother`.

`Object Mother` pattern gives us the benefits of auto generating dummy data plus force it to fixed value if required.

## Implementation

In our example case we need a `UserNameMother` and `UserMother` classes. Let's see how to implement them:

```php
class UserNameMother
{
	public static function create(?string $value = null): UserName
	{
		$random = ['Marc', 'Anna', 'Júlia', 'Ivet'];

		return new UserName($value?->value() ?? $random[rand(0, count($random) - 1)]);
	}
}

class UserMother
{
	public static function create(?UserName $name = null): User
	{
		return new User($name?->value() ?? UserNameMother::create()->value());
	}
}
```
We have set 4 different names that will be set randomly, but using a fake data provider like [FakerPHP](https://fakerphp.github.io/) we can achieve a bigger set of data.

## Usage

Let's see how to use it in our test.

```php
class SomeTest extends TestCase
{
    /** @test */
    public function itShouldAssertSomething(): void
    {
    	$user = UserMother::create();

    	$this->assertNotNull($user->name());
    }
}
```

Sometimes we need to have a no random attribute, so we can force it. In the next example, we force the name to 'John' value:

```php
class SomeTest extends TestCase
{
    /** @test */
    public function itShouldAssertSomething(): void
    {
    	$user = UserMother::create(
    		UserNameMother::create('John')
    	);

    	$this->assertEquals('John', $user->name()->value());
    }
}
```

If we had more attributes, depending on the test, we can combine random and fixed values.

## Conclusion

Our example is really simple and silly, but imagine the flexibility of that approach; your tests can use a huge amount of combinations when required giving them more strength and coverage.


Special thanks to [Christian Puga](https://twitter.com/cpuga05)
Kinx v1.0.3 Relaeased.
Tags: kinx, javascript, ruby
Published: 2021-08-12 10:20:05

Hello everyone!

I published Kinx v1.0.3 as an official release. See [Release Page](https://github.com/Kray-G/kinx/releases) for details or I put the history since v1.0.0 at the bottom of this article.

* Reference
    * First motivation ... [The post of introduction](https://dev.to/krayg/kinx-as-a-script-language-4iko)
        * Kinx, I wanted a scripting language with a syntax of C family.
    * Repository ... https://github.com/Kray-G/kinx
        * I am waiting for pull requests.

Any comments are welcome.
And also I'll wait for a star on Github!

See you!

---

## Change Log

Here is a change log since v1.0.0.

### V1.0.3 (Officially Released) - 2021/08/10

*   Improvements
    *   #308: Improvement of the stack usage.
    *   Some feedbacks from V1.1.0.
        *   Supported putting a comma at the end of an argument's list for both declaration and calling.
*   Bug Fixed
    *   #302: Fixed a prblem of the string optimization.
    *   #305: Fixed a prblem of no POPC in try.

### V1.0.2 (Officially Released) - 2021/05/21

*   Bug Fixed
    *   #284: Fixed a segmentation fault problem on Linux.
    *   #288: Incorrect message is displayed when `File.open` failed.
    *   #289: `File.setFiledate` does not work correctly.
    *   #293: Fixed a problem of a stack overflow with `=~` or `!~`.

### V1.0.1 (Officially Released) - 2021/04/22

*   Improvements
    *   Improved type analysis for the language server.
    *   Improved Array.keySet() for `Array` itself.
    *   #264: Supported to change directory.
    *   #265: Supported `$pwd` for getting a current directory.
*   Bug Fixed
    *   #235: Crash when using `_` outside a function.
    *   #236: Can't specify the class as a return type of function.
    *   #237: Comparing between variables having a string is failed.
    *   #256: Comparison operator will be failed with an integer on LHS and a variable(double) on RHS.
    *   #257: Fails a destructuring assignment when declaration with const.
    *   #258: There is a case that the bytecode is not outputted.
    *   #267: Can't use a variable name using an upper case in debugger.
    *   #269: Object item is removed by flatten().

### V1.0.0 (Official Release) - 2021/03/16

This is 1st official release version.
How to build a Firebase GUI/Admin Panel - DronaHQ
Tags: showdev, news, firebase, tutorial
Published: 2021-08-12 09:49:42

Although Firebase provides a variety of powerful functions like authentication, real-time database, firestore, and hosting, it lacks an efficient GUI to easily perform CRUD operations, view statistics, and other charts & graphs. 

This can easily be fixed by integrating [Firebase with DronaHQ](https://www.dronahq.com/) and building a quick application to manage all your Firebase data in under 30 minutes 

[![How to build firebase gui](http://img.youtube.com/vi/_fLvpzoUr9c/0.jpg)](http://www.youtube.com/watch?v=_fLvpzoUr9c)
Testing navigation in react
Tags: react, testing, reactrouter
Published: 2021-07-18 21:02:37

---
title: Testing navigation in react
published: true
description: How to test navigational redirects in a React component
tags: #react #reactjs #testing #reactrouter
//cover_image: https://direct_url_to_image.jpg
---
When testing navigation in a React component we can either check the final url or we can verify the updated DOM.

**Test scenario 1**: Test that clicking the **about** link will *redirect* to About Us path. This could be useful in scenarios where you are computing query params and want to assert on their values. 

To make assertion on url possible we will have to use Router component (react-router-dom) with our own history object. Note that when using this approach the rendered markup won't get updated to reflect navigational changes.

**Test scenario 2**: Test that clicking the **about** link will *render* About Us path. This is preferred approach and useful in scenarios where DOM content changes after navigation.

To make assertions on updated DOM we will use BrowserRouter component (react-router-dom). Note that when this approach history won't be available to the test.

```
/* file: index.js */
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {BrowserRouter} from "react-router-dom";

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </React.StrictMode>,
    document.getElementById('root')
);

/* App.js */
import {Link, Route} from 'react-router-dom';

function App() {
    return <div>
        <h1>MyApp</h1>
        <nav>
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/about">About</Link></li>
            </ul>
        </nav>
        <div>
            <Route path="/" exact>
                <h2>Home page</h2>
            </Route>
            <Route path="/about">
                <h2>About Us</h2>
            </Route>
        </div>
    </div>
}

export default App;

/* App.spec.js */
import { render, screen} from '@testing-library/react';
import {BrowserRouter, Router} from 'react-router-dom';
import userEvent from "@testing-library/user-event";
import {createMemoryHistory} from 'history';
import App from './App';

test('should redirect and update history', () => {
    const history = createMemoryHistory();

    render(<Router history={history}><App/></Router>);

    userEvent.click(screen.getByText(/About/));

    expect(history.location.pathname).toEqual('/about');
});

test('should redirect and update dom', () => {
    render(<BrowserRouter><App/></BrowserRouter>);

    userEvent.click(screen.getByText(/About/));

    expect(screen.getByText(/About Us/i)).toBeInTheDocument();
});
```
FREE UI template for Download
Tags: beginners, design, uiset, template
Published: 2021-08-12 09:02:51

*We share 100% Free and unique template of UI design with Figma, created for Pizza restaurants, Pizza chains, or related restaurant businesses.*
## Pizzario - Full UI kit for rapid restaurant ordering website
Focusing on Food-order flow, Pizzario UI set covers drop-down menus with multi selections, additional seasoning options, order screen to review. This kit offers a clear flow and clean interface for catching dinner's eyes with a vibrant and colorful look.
![UI design template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/df0lu34lrd15pv0996bg.png)
![UI design mock up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fuklf5j4wrlqk5qi6xga.png)
We open the full-editing option to purchasers in making changes to the design within the Figma desktop or app.
##[Download Now](https://inspire.adamodigital.com/restaurant-ordering-website)
**Items Included:**
*Our design expert offers clean, user-friendly UI designs, which are ready to use. With comprehensive experience in both development and design, we guarantee our design products coming with high practicality. That design came from our authentic project with a high level of applicability and clear to code.* 

| Screens       | Description   |
| ------------- |:-------------:|
| Home page     | drop-down menus, shopping cart, and popup order review. |
| Menu drop-down| allow selections and add-on extra option|
| Order page| select your dishes with the noted extra requirement|
|Add-on selection| full option of extra ingredients|
|Order review page| full order review, fee calculation, promotion code box|
|Check out page| Shipping information and series payment methods|
##[Get UI set](https://inspire.adamodigital.com/restaurant-ordering-website)
####About Author
We are Adamo Digital, a professional software design, and [software development company](https://adamosoft.com/), specializing in Travel, Hospitality, Food, Education, and Social media. Adamo Digital has done series of mobile app and web application development projects for over 30 clients In Europe, Australia, and Europe with five-star ratings.  Our design expert offers clean, user-friendly UI designs, which are ready to use. With comprehensive experience in both development and design, we guarantee our design products coming with high practicality. Check our profile below.
New to Pyrogram? Take a look here.
Tags: python, pyrogram, telegram, bot
Published: 2021-08-12 08:57:13

### Define a client in different way:
`/main.py`:
```python
import pyrogram

client = pyrogram.Client("Session-Name")
```
`/config.ini`:
```ini
[pyrogram]
api_id=1234567
api_HASH=1108f129f7afa345076448421e535bbd
bot_token=1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
```
You can get your `api_id`, `api_hash` from [telegram](https://my.telegram.org/apps). And, you can get the token from [`@botfather`](https://telegram.me/botfather)


---


### Do long time process, without disturbing the bot
```python
import _thread

def some_long_process(param1, param2):
    # do something that takes long time
    param2.reply_text('Process Over.')
    ...


@client.on_message(
    pyrogram.filters.command('do_big')
)
def do_big(_c, message):
    _thread.start_new_thread(some_long_process, (_c, message))
```
You can pass on the `client` and the message `parameter` to some function, which takes a long time to complete, and has to notify the user when it completes. During this process, some times the bot might stop responding to other users, or become slow.

So, use `_thread` module to start a new thread which runs `in background` without disturbing your bot, and making it faster to the core.
My Thoughts on SuperTokens
Published: 2021-08-12 15:31:50

---
title: My Thoughts on SuperTokens
published: true
date: 2021-08-12 08:15:00 UTC
tags: 
canonical_url: https://blog.kapic.io/supertokens/
---

![SuperTokens Thumbnail](https://blog.kapic.io/assets/img/supertokens.png)

Authentication has been a topic of fascination for me over the last several months. I have been researching all of the available options that I can find. If you follow me on [YouTube](https://www.youtube.com/channel/UCuXgDzDJhNAwvzvc62GnYwA), then you might have seen my [video](https://www.youtube.com/watch?v=kPK4Cra_I5I) about authentication methods. Since creating that video, I stumbled upon [SuperTokens](https://supertokens.io/), and I have to say... I am impressed.

That being said, SuperTokens is for a specific use case—web apps created with `create-react-app`. Technically, it works with other libraries as well, but I think other options are better for projects built with Gatsby, other JavaScript frameworks, or native applications—At least for now (I am actually a contributor for SuperTokens, and in the future I plan on working on bringing ease-of-use to Gatsby and maybe Expo for native applications).

SuperTokens is good for several reasons:

- It is simple to set up (with `create-react-app`).
- It is open source.
- You can easily self-host it (I'm working on the CapRover One-Click App).
- It integrates with your Node.js API.

Some of the (current) drawbacks of SuperTokens include:

- There are not supported SDKs for other frameworks.
- There are not supported SDKs for other backends.

Keeping in mind these limitations, this is the _perfect_ use case for SuperTokens:

**SaaS web application built with CRA on a subdomain**

Let me explain.

You probably do not want to use `create-react-app` for a landing page because you want to optimize SEO. So instead, you choose Next.js or Gatsby. But those are annoying to build apps in, so you use `create-react-app` for the app itself. Host the app on `https://app.yourdomain.com` and the landing page on `https://yourdomain.com`. Then **boom**. Easy authentication with better SEO. And your authentication is not bound by vendor lockin because you can selfhost it.

This is my current strategy for TickerTab.
How Can I Implement the Function of Touching and Holding an Image to Save It in Quick Apps
Tags: huawei, quickapps, android
Published: 2021-08-12 08:00:10

#Scenario Description

WeChat mini programs allow you save images to the album by touching and holding them. Currently, HUAWEI Quick App does not have any API to implement this function, but you can trigger events to implement this function

All quick app elements support the longpress event. So you can use the image element to render images and trigger the longpress event on the element to implement the function.

#Sample code

{% gist https://gist.github.com/devwithzachary/c410fcfceba02fc2de32be20b2f20361 %}

Reference: [Quick app reference](https://developer.huawei.com/consumer/en/doc/development/quickApp-References/quickapp-common-settings)
break in forEach? 🤔
Tags: codesandbox, javascript
Published: 2021-08-12 07:49:27

# Conclusion first

We cannot `break` in `forEach` loop 

# What are the alternatives

- `for of` : [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)

=> You might get eslint error
[no-restricted-syntax - Rules - ESLint - Pluggable JavaScript linter](https://eslint.org/docs/rules/no-restricted-syntax)

- `some` or `every`

Here is the case with `some()`
[Array.prototype.some() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)

returning `true` break the loop 👍

![Image 2021-08-12 at 4.45.30 PM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohx67trtmozkmam9tcah.jpg)

{% codesandbox s44po %}

# Reference

- [for...of を使うなってAirbnbが言ってたから使わないようにしてたら慣れた - Qiita](https://qiita.com/41semicolon/items/6ec0f6a9fdf7c97f1a41)
- [javascript - Short circuit Array.forEach like calling break - Stack Overflow](https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break)
Lazy loading Angular
Tags: angular, typescript, rxjs, lazyloading
Published: 2021-08-12 07:39:05

Lazy loading is the best way to separate component into different modules. For large application lazy loading help structure routes for easy readability and fast page  load.

##### How to setup lazy loading in angular 


1.Create Modules for route you intent to lazy load

```
ng g m @module/main --routing
```

2.Add components to the new module created

```
ng g c components/home --m @module/main
```
This automatically adds home to the main module

3.Setting up route in main module 

```
const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  }
];

```
4.Finally lazy load Main Route in your application route or (App Route)

```
const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./main/main.module').then(m => m.MainModule)
  }
];

```
Thanks for reading