teleren/devto huggingface dataset:
react中useStateCallback的封装
Published: 2023-02-20 09:50:42

target:当state更新后，调用回调函数

- useEffect会在state的数据变化后

- useRef存储、调用回调函数
 
###Package
```typescript
import { useEffect, useRef, useState } from "react"

export const useStateCallback=<T>(initialState: T | (() => T))=>{
  const [state, setState] = useState<T>(initialState)
 const ref= useRef<any>()
  const setStateCallback=(value: T | ((prevState: T) => T),callback:Function)=>{  
    ref.current=callback
     setState(value)
  }
  useEffect(() => {
    ref.current&&ref.current(state)
  }, [state])
  return {state,setStateCallback}
}
```
###Call
```typescript
import { Button } from 'antd'
import { useStateCallback } from './hooks'

 const App = () => {
 const {state,setStateCallback}= useStateCallback<number>(1)
  const click=()=>{
    setStateCallback(state=>state+1,(stateUpdated:number)=>{
      console.log("after updating data",stateUpdated);
    })
  }
  return (
    <div>  
     count:{state}
     <Button onClick={click}></Button>
   </div>
  )
}
export default App
```
###Outcome

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51fmhmk4m7c73w2t94x2.png)
create-react-app vs vite
Tags: webdev, programming, react
Published: 2023-02-20 09:21:13

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfdk3v7udn9ttt7mx0hw.png)
create-react-app and vite are both tools for building and configuring front-end web applications, but they have some key differences.


**create-react-app** is a command-line tool for creating React applications with no configuration required. It sets up a development environment with all the necessary dependencies and configurations for building a React app. It includes a built-in web server, and supports features like hot reloading, code splitting, and linting out of the box. create-react-app is a good choice if you're just getting started with React and want a simple way to get up and running quickly.

On the other hand, **vitet** is a build tool that supports multiple front-end frameworks, including React. It's designed to be faster than traditional build tools like webpack, by using native ES modules and leveraging browser cache. vite provides a highly optimized development experience, with fast build times and hot module replacement. It also supports features like dynamic imports and tree-shaking, which help to reduce the size of your app and improve its performance. vite is a good choice if you want a highly performant build tool and are comfortable with configuring your project.

Overall, both **create-react-app** and **vite@latest** are excellent tools for building React applications, but they have different strengths and use cases. If you're new to React and want to get started quickly, create-react-app is a good choice. If you're comfortable with configuration and want a highly optimized build tool, vite@latest is worth considering.
C# career
Published: 2023-02-20 09:41:52

Hello, I'm a BSCS student and currently it's mid of my degree. Someone recommended me to learn C#. I have researched this but found C# in the middle or somewhere in the bottom of rating. Js, python, solidarity, swift, java, etc. are becoming popular. As we know that AI is becoming more advance with the launch of chapgpt, midjournery, upcoming AI BARD of google. kindly someone give me honest guide to make my programming career bright. Thanks
How to Upgrade Laravel 9 to Laravel 10 .
Published: 2023-02-20 09:40:55

**Laravel 10 is officially released** 
Today I will show how to upgrade laravel 9 to [laravel 10](https://laravel.com/docs/10.x/upgrade).

**Updating Dependencies**
`PHP 8.1.0 Required`
Laravel now requires `PHP 8.1.0 or greater`.

**Composer 2.2.0 Required**
Laravel now requires [Composer](https://getcomposer.org/) 2.2.0 or greater.

Composer Dependencies
You should update the following dependencies in your application's `composer.json` file:


```
1.laravel/framework to ^10.0

2.laravel/sanctum to ^3.2

3.spatie/laravel-ignition to ^2.0

4.nunomaduro/collision to ^7.0

5.phpunit/phpunit to ^10.0

Update your composer. Run this command

composer update.

```

Hope that work it . Happy Coding and Learning .
Writing a basic Feature Test with PhpUnit in Laravel
Tags: testing, laravel, phpunit
Published: 2023-02-20 09:09:57

Create Event controller, migration, model and seed some datas.

php artisan make:test EventTest

Browse to tests/Feature/EventTest.php


We are going to check if Event::all is returning properly with a JSON structure:

```php
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use App\Models\Event;

class EventTest extends TestCase
{
    /**
     * A basic feature test example.
     */
    public function test_example(): void
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

    public function test_for_get_all_events()
    {
        $events = Event::all();
        $resposne = $this->get('/view')->assertStatus(200)->assertJsonStructure(
            [
                'code',
                'message',
                'data' =>
                [
                    [
                    'id',
                    'name',
                    'country',
                    'random_no',
                    'created_at',
                    'updated_at'
                    ],
                ],
            ]
        );
    }
}

```

Function which is being tested:
```php 
public function view(): String
    {
        $a = Event::all();
       

        return json_encode([
            'code' => 200,
            'message' => 'Successful',
            'data' =>$a
        ]);
    }
```

To run tests exec: `php artisan test`

The function's Json structure matches with the Test's JSON structure hence the test passes


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpruxde5218itg1hvm77.png)
How did I upgrade Aurora Postgres RDS clusters in Production using Terraform
Tags: aws, rds, devops, terraform
Published: 2023-02-20 08:35:07


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ivn3s92we3ztbey1xm1.png)

Step by Step Guide which includes
- Planning required for the upgrade
- Usage of terraform module and version dependency
- Detailed steps for minor/major version upgrade
- Problems faced and their solutions as part of upgrade
- Best Practices for Database major version Upgrade

Take a look at detailed article - https://faun.pub/how-did-i-upgrade-aurora-postgres-rds-clusters-in-production-using-terraform-ff57aeb16873?source=friends_link&sk=26630c75421b705ad15b36f622feaddb
6 git commands, you may not know.
Tags: webdev, laravel, javascript
Published: 2023-02-20 08:20:02

TABLE OF CONTENTS

```
1) Updating the last commit message.
2) Blank Commit.
3) Checking the total number of commits.
4) Checking files from different a branch.
5) Staging (adding) and committing the changes in a single command.
6) Git tutorial on the terminal.

```
Here are some of the top `git` commands which I handpicked, that can be useful to increase your productivity, and also save your some time.


**1) Updating the last commit message.**
If you want to update the message of your last commit, because either it didn't look conventional or meaningful, use this command to edit it:

```
git commit --amend -m "Updated message"
```

**2) Blank Commit.**
Sometimes we need a blank commit (no changes added or deleted) maybe we need to initialize our repo or trigger some kind of action, we can use this command:


```
git commit --allow-empty -m "blank commit message"
```


**3) Checking the total number of commits.**
If we want to check the total no of the commit on a particular branch we can use this command.

```
git rev-list --count <branch-name>


Example:


git rev-list --count main

```
**4) Checking files from different a branch.**
If we want to view some files from a different branch while working on a different branch, we can use this command:


```
git show <branch-name>:<file-name>
```
For Eg: If we are working on the `test` branch and want to see the `README.md` file of the `main` branch, we can use this command:

```
git show main:README.md

```

**5) Staging (adding) and committing the changes in a single command.**
Instead of doing `git add` and` git commit` separately, we can use this single command to perform this:


```
git commit -am "message"
```

**6) Git tutorial on the terminal.**
Yes!,you heard is right, with only single command use can have a whole git tutorial at your fingertips.

```
git help tutorial
```

Share with your friends.
GitHub CMake cross-compile action workflow example
Tags: github, beginners, productivity, programming
Published: 2023-02-20 08:13:02

For my [C++ project](https://github.com/aregtech/areg-sdk/) at GitHub i wanted to create an _action workflow_ to compile sources. At first, i used the CMake workflow template offered by GitHub (those who are not familiar much with GitHub, in **Actions** tab select _New Workflow_), and compiled only with GCC under Linux.
![AREG SDK GitHub Action workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nltgdfpjvgecqmjb85mc.png)

But the agenda was to compile sources using multiple compilers and platforms. Since I was not familiar with YAML, I started to search and looked many examples of complex workflows to combine in one file. The alternative would be creating one workflow per compilation, which I considered not much efficient. Finally, I've created an action workflow, which compiles with _gcc/g++_, _clang/clang++_ and _msvc_ under **Linux** (Ubuntu), **Windows** and even **Cygwin**. Here I share the link to the [CMake Workflow](https://github.com/aregtech/areg-sdk/blob/master/.github/workflows/cmake.yml). I find it very useful, helps to save time to check cross-compilation after every push. Can be useful and good example for other projects.
May the (Push) Force be with you
Tags: git, github
Published: 2023-02-20 08:08:50

## Introduction
As a novice developer, I used to fear the power of the push force command. However, I've come to realize that it's an incredibly useful tool as long as it's used wisely.

When I commit my code, I always try to include a meaningful message. If I make additional changes but don't want to create another commit, I simply amend the existing commit and push it using the force command. 

## Example 
For example, if I make changes to the coffee.rb file in my app, I can use the following commands to avoid creating another commit:

Supposing you made changes in your coffee.rb file, on your feature branch you can do the following command to avoid adding another commit :

```
git add coffee.rb
git commit --amend --no-edit
git push -f
```

Of course **do not push force on main or develop**. 
Most of the time you will be not able or authorize to do it anyway. 
Push force is not a bad tool, as all tools you have to learn how to use it the right way. If you do so you will improve your workflow a lot. 

By the way if you rebase you already push force a lot.

## Tips 
If you are not sure where you are on the branch you can use the following git command, this will show you where is your head commit.
```
git log --oneline --graph
```

## Conclusion
As a junior developer, I still have a lot to learn. I often feel apprehensive about using certain tools or making changes to the codebase. My advice to others in the same boat is to take the plunge and ask more experienced colleagues for their reviews and advice.
A sequential work queue for typescript in 11 lines of code
Tags: typescript, queue
Published: 2023-02-20 08:06:07

```typescript
class WorkQueue<T> {
  private lastJob: Promise<T> | undefined

  async queueWork(work: () => Promise<T>): Promise<T> {
    const nextJob = this.lastJob = this.lastJob?.then(work, _ => {}) ?? work()
    try {
      return await nextJob
    } finally {
      // ensure previous results can be garbage collected
      if (nextJob === this.lastJob) { this.lastJob = undefined }
    }
  }
}
```

Okay maybe you should use a few more lines to be clearer but I like how neat this is.
HOW TO CREATE A LINUX VIRTUAL MACHINE ON MICROSOFT AZURE
Tags: azure, cloud
Published: 2023-02-20 07:21:47

STEP 1
 login to your Microsoft azure account and navigate to the search resources and search "virtual machines"



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhalm3ua0ssdd5x4c5t4.png)

STEP 2
Click on create and select azure virtual machines


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyuws4qrmr7pepb4naxf.png)
STEP 3

Fill out the necessary fields, select your resource group



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikapqi5si8hq2bdsl8ha.png)

STEP 4
Give your virtual machine a name

Virtual Machine Name: input a name for your virtual machine
Region: select a region where the virtual machine will be located
Availability option: availability zone
Zone: select any zone of your choice
security type: standard
Image: select the base operating system you prefer



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/533cztontomwuqnhpfqu.png)

STEP 5

click on SSH public key and input any username of your choice
then click on review and create


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyvtskan1ghi747qle11.png)


STEP 6

download the private key file and continue



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljcau40drwoj02o8olr4.png)

STEP 7
go to resource


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eisgfgbwr9npgp01tl3m.png)

STEP 8

click on your public Ip address to extend your idle timeout frame



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sv8ynwjmefh5rbp1xhi8.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3oyjn300b00ofu64odr.png)

then click save



STEP 9
go back to your virtual machine and click on connect and select SSH



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/am5c6ec4mijtz81e9vru.png)

STEP 10

Go to your windows search menu and search for powershell.
open your powershell



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehdvoqw6uc78o7ayzou6.png)

STEP 11

go to the folder you downloaded your private key and right click to copy the path of the file



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oztxljova2xthpy4p8a7.png)

 paste the copied path in the private key path on your azure portal



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3i0a3utvnw1pg1k18yv.png)


STEP 12

copy the command to your clipboard



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74qmoh4ks9p3iv0wu7rf.png)


go to your powershell and paste the code then hit enter



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wt5myy2fqo41l9n9kros.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndv4xarodtkmo64549dk.png)






Enjoy!!!!
Update your npm dependencies and your package.json at once !
Tags: npm, webdev, javascript, programming
Published: 2023-02-20 07:10:00


I recently stumbled upon an new feature of Composer added on 06/22 named `composer bump` ([see this post](https://php.watch/articles/composer-bump)) which brings a good way to keep track of the updates made to your repository.

As we all know, versionning is essential for the following reasons : 
- Ability to rollback to a previous version of your code
- Collaborate and handle merge conflicts
- You can **travel back in time** to know when a piece of code was modified

That’s why "updating" your `composer.json` at the same time as running `composer update` can be a way to know what happened when something goes wrong later.

![Composer bump is a great feature](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxek5iienynpwk8fd7rw.png)

> In the end we have something clear and tracked in time

## What about NPM ?

While doing my chores on a React project i looked for a similar feature with NPM (Node package manager), but surprisingly there is no such thing ! 

![Chat gpt answer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjgrvrqkbom52sejcnrt.png)

> Chat-GPT struggled with my question... A LOT 😅 Npm version is not the right answer.

## The savior: NCU

Sometimes, you’re just glad to find a package that makes everything that you need, and even more. The chosen one is [Npm check update](https://www.npmjs.com/package/npm-check-updates) made by **[Raine Revere](https://dev.to/raineorshine)** and it allows you to : 

- List all new dependencies
- Interactively upgrade them
- Upgrade your package.json

So if you want to have a package.json file up to date with your locked dependencies just install the package globally

`npm install -g npm-check-updates`

And run `ncu -u` to upgrade your `package.json` 
**Don’t forget** to run `npm install` to install the updates and to renegerate your `package-lock.json`

You'll end up with this nice diff while commiting your dependencies update

![Package.json upgrade with NCU -u](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgimd5nwfh1rshqw5unv.png)

Hopefully it was useful to you 👋
Does anybody here know how to draw an image onto a canvas and at the same time be responsive without sacrificing the resolution.
Tags: javascript, webdev, react, css
Published: 2023-02-20 07:09:18


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oed5hdqmnj8erib24q1l.png)

description:

Does anybody here know how to draw an image onto a canvas and at the same time be responsive without sacrificing the resolution. The thing is i need to draw some rectangles on the image and make the canvas responsive with the image
Figma in 100 seconds
Tags: figma, tutorial, beginners, webdev
Published: 2023-02-20 07:05:55

{% youtube PRnNqg-Uz9o %}
Hello everybody, today we want to learn you everything's need to know about Figma in 100 seconds.
Figma is a platform where teams design together, It Works on any platform and can be used pretty much to create any things like Logos, Apps, Websites, and much more.
Figma uses slack for team communication and Files provides real-time updating, All you need to start using it is a computer with a good browser and an internet connection then You can go to Figma’s website and sign up for a free account, so you can start working on your designs right away!
Figma was launched on September 27, 2016 by Dylan Field and Evan Wallace.
Today, Figma is part of the Adobe ecosystem; Adobe completed its purchase of the company in September 2022 for $20 billion.

Now we will look at some of the advantages of Figma:
Easy to share files
A complete solution for creating design prototypes
Cloud-based website designing tool
Powerful Tools
No Need to Save Your Work

The following are the disadvantages of Figma:
No Version Control
Limited Customization Options
Cannot Work Offline

If you enjoyed this video, don't forget to hit the subscribe button, so you never miss an update from us.

Let's be friends and connect
📩 Subscribe:https://shorturl.at/BCTV8
📷 Instagram: https://www.instagram.com/soudemy/
📱 Behance: https://www.behance.net/soudemy
🐦 Twitter: https://twitter.com/SoudemyAcademy

In the comments, you can say what design you want so that we can prepare the video for you.
Asking for a pay rise in 2023
Tags: career, discuss, help, watercooler
Published: 2023-02-20 07:03:24

With all the tech layoffs happening it feels like a bad time to be asking for a pay rise. But cost of living is increasing, and inflation is still ongoing.

What is your advice to an engineer who believes they deserve a pay rise (several years in same company, increasing responsibilities, good performance)? How would you go about approaching your manager? And would you discuss this issue with your colleagues also?
Theorem Every Developer Should Know: CAP
Tags: beginners, programming, tutorial, computerscience
Published: 2023-02-20 06:58:03

> CAP theorem briefly; argues that in a distributed architecture, there cannot be Consistency, Accessibility and Partition Tolerance at the same time.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lr2xojlb1wjg8faasc1m.png)

**Consistency:** Let there be two servers named x and y in the distributed system. When we request it, it will give the e-mail address of the user named “furkan” from the X server. If the e-mail value received in return for the "furkan" username from server y is the same as the e-mail value received in X, consistency is ensured here.

**Availability:** Distributed systems should always be available. If there are only two servers named X and Y in the distributed system, both servers should always be available.

**Partition Tolerance**: X and Y servers are interconnected. If server X goes down for any reason, server Y should be able to continue running. 

So why does the CAP theorem claim that these three properties cannot exist simultaneously? Let's take a look at them now...

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tqaobmebe9d9f0apgn2.jpg)


## CP Defenders

- Availability was sacrificed.
- It is based on Consistency and Partition Tolerance.
- Closing the inconsistent node when a split occurs between two nodes.

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qzkmy8mg1739i2vezlj.png)

## AP Defenders

- Consistency is sacrificed.
- It is based on Availability and Partition Tolerance.
- When a split occurs between two nodes, access to both will be available. However, the database to which either node is connected is not guaranteed to be the same. In this case, there is no consistency between the two nodes.

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9n28okwvnm7wolybsl8k.png)

## CA Defenders

- The Partition Tolerance property has been sacrificed.
- It is based on Availability and Consistency.
- All nodes are accessible and each node is consistent with each other. No division can occur between nodes.