React Hooks: Array Destructuring Fundamentals - Opencodesolution.Com ...

Tuesday, 26 July 2022

React Hooks: Array Destructuring Fundamentals - Opencodesolution.Com

React Hooks: Array Destructuring Fundamentals

This is the first example on the https://reactjs.org/hooks documentation:

import {useState} from 'react'

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  )
}

That const [count, setCount] = useState(0); is the line we're going to be talking about today. The syntax here is called "array destructuring" and it was introduced into JavaScript in the infamous (more than famous) ES6 release.

I'm a firm believer that:

The better you understand an abstraction, the more effective you will be at using it. – me, literally right when I wrote this...

So when I see syntax that I'm unfamiliar with, I like to read about it and understand how it works with the rest of the language. The problem is that it can be difficult to "Google" syntax. Seriously... Try Googling the syntax itself as if you didn't know that it's called "destructuring." Pretty tough! So here's my trick. I go to astexplorer.net and paste in the code that I don't understand:

Cool! Babel calls that an "ArrayPattern." So let's go ahead and Google for that. We'll search for https://developer.mozilla.org array pattern" (that way Google only returns results for articles on MDN which is a terrific resource on learning everything there is to know about JavaScript).

Sweet, the first result takes us to "Destructuring assignment" where we can learn all about this feature (I guess you can read that instead of continuing here if you want to 😅).

Often syntax like this is what we call "syntactic sugar" for other features. Here's what wikipedia says about syntactic sugar:

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

Ok, so basically it means that there are common patterns or ways to write code in a given language, so the language makes a syntax feature to make that pattern require less code or more expressive. With this in mind, when I'm learning new syntax, I like to "de-sugar" the syntax to see what it would look like if we didn't have that feature.

Luckily for us, we have Babel and TypeScript which can compile this newer syntax into something older browsers can support (and presumably to something we may be more familiar with). So my next step is to go to the online babel REPL and paste in the code. Here's what the result looks like:

'use strict'

var _slicedToArray = (function () {
  function sliceIterator(arr, i) {
    var _arr = []
    var _n = true
    var _d = false
    var _e = undefined
    try {
      for (
        var _i = arr[Symbol.iterator](), _s;
        !(_n = (_s = _i.next()).done);
        _n = true
      ) {
        _arr.push(_s.value)
        if (i && _arr.length === i) break
      }
    } catch (err) {
      _d = true
      _e = err
    } finally {
      try {
        if (!_n && _i['return']) _i['return']()
      } finally {
        if (_d) throw _e
      }
    }
    return _arr
  }
  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i)
    } else {
      throw new TypeError(
        'Invalid attempt to destructure non-iterable instance',
      )
    }
  }
})()

// const [count, setCount] = useState(0);
var _useState = useState(0),
  _useState2 = _slicedToArray(_useState, 2),
  count = _useState2[0],
  setCount = _useState2[1]

😬 YIKES! Hmmm... Ok, so sometimes Babel uses utilities which both make it more compliant to the specification, but also can make the code a little harder to understand. Luckily, there's an option on the Babel Repl's "Env Preset" called "Loose" which will simplify this output considerably:

// const [count, setCount] = useState(0);
var _useState = useState(0),
  count = _useState[0],
  setCount = _useState[1]

😌 Phew, that's better. Ok, so what's going on here. Babel's taking our one line and rather than using the Array Pattern thing, it's assigning the return value of useState to a variable called _useState. Then it's treating _useState as an array and it assigns count to the first item in the array and setCount to the second one.

Let's play around with this a little bit to explore the syntax:

 

Can I call the values whatever I want?

// const [whateverIWant, reallyICanChooseWhatItIsCalled] = useState(0);
var _useState = useState(0),
  whateverIWant = _useState[0],
  reallyICanChooseWhatItIsCalled = _useState[1]

 

Can I add more elements?

// const [count, setCount, somethingElse] = useState(0);
var _useState = useState(0),
  count = _useState[0],
  setCount = _useState[1],
  somethingElse = _useState[2]

 

Can I pull out fewer?

// const [count] = useState(0);
var _useState = useState(0),
  count = _useState[0]

 

Can I skip one?

// const [, setCount] = useState(0);
var _useState = useState(0),
  setCount = _useState[1]

 

Can I skip more?

// const [,,, wow,, neat] = useState(0);
var _useState = useState(0),
  wow = _useState[3],
  neat = _useState[5]

 

I saw someone put a weird = sign in there, what does that do?

// const [count = 3, setCount] = useState(0);
var _useState = useState(0),
  _useState$ = _useState[0],
  count = _useState$ === undefined ? 3 : _useState$,
  setCount = _useState[1]

Oooh, fancy, so if the first element of the array is undefined, then we'll set count to 3 instead. Default values! Sweet.

  • Note: most of the things above you would never need to do with useState because we can always rely on useState returning an array of two elements! We'll look at that more next.

Ok cool, so this helps us understand what's actually going on. There's nothing React-specific about this syntax. It's built-into the JavaScript specification, and React's useState hook is leveraging it as a mechanism for an ergonomic API that allows you to get two values out of a single function call. Neat!

Ok, so what does useState actually do then? What is it really returning? It must be returning an array for us to be doing the array destructuring like this right? Cool, let's check that out.

One thing that's interesting is that the implementation of useState exists within react-dom rather than react. I know, that may be confusing because we import useState from the react package, but it actually just delegates to the current renderer (which is react-dom in our situation here). In fact, setState is the same way!

 

Another interesting thing about useState is that the implementation in react-dom is just a few lines:

function useState(initialState) {
  return useReducer(
    basicStateReducer,
    // useReducer has a special case to support lazy useState initializers
    initialState,
  )
}

 

😱 it's actually just a hook that's using the useReducer hook! Ok, but what is that basicStateReducer thing huh?

function basicStateReducer(state, action) {
  return typeof action === 'function' ? action(state) : action
}

 

Ok, interesting, so useReducer is actually over 100 lines of code, so let's just look at what useReducer returns:

return [newState, dispatch]

 

See! It's an array! So when we call useState, it returns a call to useReducer which will return an array of two values. This allows us to do the array destructuring that we want so instead of writing:

const stateAndUpdater = useState(0)
const count = stateAndUpdater[0]
const setCount = stateAndUpdater[1]

 

We can write:

const [count, setCount] = useState(0)

 

Thank You ! 

Categories : React

Tags : React Js



0 Comment

Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles

Benefits of Git



Version control (sometimes referred to as source control) plays an important role in any development project, including test automation. It is the practice of tracking and providing control over changes made in the source code. And since one of the most common tools used in version control is Git, let’s get to understand some of the most common Git commands.

What are Git Commands?

Git commands are a distributed version control system for tracking changes in any set of files. They were originally designed for coordinating work among programmers who were operating source codes during software development.

Git is a fast, scalable, and distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals.

Benefits of Git

  • It’s free (and open-source): You can freely contribute to the code any time and, of course, you don’t need to purchase it, since it is open-source.
  • Performance: It is faster and more reliable than any other version control software as it focuses only on file content rather than on file names.
  • Security: Git protects the code and the change history through a cryptographically secure hashing algorithm, called SHA1.
  • Widely-used: Git has become the preferred VCS tool in many great organizations.

Most Common Git Commands

Using git –help in the command prompt (on Windows), terminal (for Mac), or shell (on Linux) will give you a list of the available Git commands:


Let’s look over some of the most useful Git commands and understand them:

git clone

This command is used for downloading the latest version of a remote project and copying it to the selected location on the local machine. It looks like this:

git clone <repository url>

To clone a specific branch, you can use

git clone <repository url> -b <branch name>

git fetch

This Git command will get all the updates from the remote repository, including new branches.

git checkout

You can use the checkout command to switch the branch that you are currently working on.

git checkout <branch name>

If you want to create a new branch and switch to it, you can do it by using this command:

git checkout -b <branch name>

git init

This is the command you need to use if you want to start a new empty repository or to reinitialize an existing one in the project root. It will create a .git directory with its subdirectories. It should look like this:

git init <repository name>

git commit

This one is probably the most used Git command. After changes are done locally, you can save them by “committing” them. A commit is like local a snapshot of the current state of the branch, to which you can always come back. To create a new commit, type this command in Git Bash:

git commit -m "<commit message>"

If all goes well, you will see the changes in the commit.

git push

Git push will push the locally committed changes to the remote branch. If the branch is already remotely tracked, simply use it like this (with no parameters):

git push

If the branch is not yet tracked, and only resides on the local machine, you need to run the command like this:

git push --set-upstream <remote branch> <branch name>

 

git diff

You can use this command to see the unstaged changes on the current branch. Here’s an example of a branch with an edited feature file:

If you want to see the staged changes, run the diff command like this:

git diff --staged

Or you can compare two branches:

gif diff <branch1> <branch2>

git pull

Using git pull will fetch all the changes from the remote repository and merge any remote changes in the current local branch.

git add

This is the command you need to use to stage changed files. You can stage individual files:

git add <file path>

Or all files:

git add .

git branch

Using git branch will list all the branches of the repository:

Or you can use it to create a new branch, without checking it out:

git branch <new branch>

To delete a branch, run it like this:

git branch -d <branch name>

Conclusions

Git can be a really powerful tool in any development project and you will probably use most of these commands on a daily basis if your team uses Git for version control.

https://opencodesolution.com/

Monday, 25 July 2022

Laravel 8 CRUD Tutorial by Example


 

How Does it Work?

Laravel 8 CRUD operation application; In this tutorial, you will learn step by step how to build simple crud operation app in Laravel 8. And how to validate add & update form data on server-side in Laravel 8 crud app.

CRUD Meaning: CRUD is an acronym that comes from the world of computer programming and refers to the four functions that are considered necessary to implement a persistent storage application: create, read, update and delete.

This Laravel 8 crud operation step by step tutorial will implement a simple company crud operation app in Laravel 8 app with validation. Using this crud app, you can learn how to insert, read, update and delete data from database in Laravel 8.

Laravel 8 CRUD Tutorial by Example

Step 1 – Download Laravel 8 App
Step 2 – Setup Database with App
Step 3 – Create Company Model & Migration For CRUD App
Step 4 – Create Routes
Step 5 – Create Company CRUD Controller By Artisan Command
Step 6 – Create Blade Views File
Make Directory Name Companies

index.blade.php
create.blade.php
edit.blade.php


Step 7 – Run Laravel CRUD App on Development Server

Step 1 – Download Laravel 8 App

First of all, download or install laravel 8 new setup. So, open the terminal and type the following command to install the new laravel 8 app into your machine:

composer create-project --prefer-dist laravel/laravel LaravelCRUD

 

Step 2 – Setup Database with App

Setup database with your downloaded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

 

Step 3 – Create Company Model & Migration For CRUD App

Open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Company -m

After that, open create_companies_table.php file inside LaravelCRUD/database/migrations/ directory. And the update the function up() with following code:

public function up()
{
   Schema::create('companies', function (Blueprint $table) {
       $table->id();
       $table->string('name');
       $table->string('email');
       $table->string('address');
       $table->timestamps();
   });
}

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

 

Step 4 – Create Routes

Then create routes for laravel crud app. So, open web.php file from the routes directory of laravel CRUD app. And update the following routes into the web.php file:

use App\Http\Controllers\CompanyCRUDController;

Route::resource('companies', CompanyCRUDController::class);

 

Step 5 – Create Company CRUD Controller By Artisan Command

Create a controller by using the following command on the command prompt to create a controller file:

php artisan make:controller CompanyCRUDController

After that, visit at app/Http/controllers and open CompanyCRUDController.php file. And update the following code into it:

<?php
namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;
class CompanyCRUDController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data['companies'] = Company::orderBy('id','desc')->paginate(5);
return view('companies.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('companies.create');
}
/**
* Store a newly created resource in storage.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'address' => 'required'
]);
$company = new Company;
$company->name = $request->name;
$company->email = $request->email;
$company->address = $request->address;
$company->save();
return redirect()->route('companies.index')
->with('success','Company has been created successfully.');
}
/**
* Display the specified resource.
*
* @param  \App\company  $company
* @return \Illuminate\Http\Response
*/
public function show(Company $company)
{
return view('companies.show',compact('company'));
} 
/**
* Show the form for editing the specified resource.
*
* @param  \App\Company  $company
* @return \Illuminate\Http\Response
*/
public function edit(Company $company)
{
return view('companies.edit',compact('company'));
}
/**
* Update the specified resource in storage.
*
* @param  \Illuminate\Http\Request  $request
* @param  \App\company  $company
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'address' => 'required',
]);
$company = Company::find($id);
$company->name = $request->name;
$company->email = $request->email;
$company->address = $request->address;
$company->save();
return redirect()->route('companies.index')
->with('success','Company Has Been updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param  \App\Company  $company
* @return \Illuminate\Http\Response
*/
public function destroy(Company $company)
{
$company->delete();
return redirect()->route('companies.index')
->with('success','Company has been deleted successfully');
}
}

 

Step 6 – Create Blade Views File

Create the directory and some blade view, see the following:

Make Directory Name Companies
index.blade.php
create.blade.php
edit.blade.php
 

Create directory name companies inside resources/views directory.

Note that, create index.blade.php, create.blade.php and edit.blade inside companies directory. And update the following code into following files:

 

index.blade.php : 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Laravel 8 CRUD Tutorial From Scratch</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Laravel 8 CRUD Example Tutorial</h2>
                </div>
                <div class="pull-right mb-2">
                    <a class="btn btn-success" href="{{ route('companies.create') }}"> Create Company</a>
                </div>
            </div>
        </div>
        @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
        @endif
        <table class="table table-bordered">
            <tr>
                <th>S.No</th>
                <th>Company Name</th>
                <th>Company Email</th>
                <th>Company Address</th>
                <th width="280px">Action</th>
            </tr>
            @foreach ($companies as $company)
            <tr>
                <td>{{ $company->id }}</td>
                <td>{{ $company->name }}</td>
                <td>{{ $company->email }}</td>
                <td>{{ $company->address }}</td>
                <td>
                    <form action="{{ route('companies.destroy',$company->id) }}" method="Post">
                        <a class="btn btn-primary" href="{{ route('companies.edit',$company->id) }}">Edit</a>
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger">Delete</button>
                    </form>
                </td>
            </tr>
            @endforeach
        </table>
        {!! $companies->links() !!}
</body>

</html>

 

create.blade.php:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Add Company Form - Laravel 8 CRUD</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left mb-2">
                    <h2>Add Company</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('companies.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if(session('status'))
        <div class="alert alert-success mb-1 mt-1">
            {{ session('status') }}
        </div>
        @endif
        <form action="{{ route('companies.store') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Name:</strong>
                        <input type="text" name="name" class="form-control" placeholder="Company Name">
                        @error('name')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Email:</strong>
                        <input type="email" name="email" class="form-control" placeholder="Company Email">
                        @error('email')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Address:</strong>
                        <input type="text" name="address" class="form-control" placeholder="Company Address">
                        @error('address')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
</body>

</html>

 

edit.blade.php:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Edit Company Form - Laravel 8 CRUD Tutorial</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Edit Company</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('companies.index') }}" enctype="multipart/form-data">
                        Back</a>
                </div>
            </div>
        </div>
        @if(session('status'))
        <div class="alert alert-success mb-1 mt-1">
            {{ session('status') }}
        </div>
        @endif
        <form action="{{ route('companies.update',$company->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Name:</strong>
                        <input type="text" name="name" value="{{ $company->name }}" class="form-control"
                            placeholder="Company name">
                        @error('name')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Email:</strong>
                        <input type="email" name="email" class="form-control" placeholder="Company Email"
                            value="{{ $company->email }}">
                        @error('email')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Address:</strong>
                        <input type="text" name="address" value="{{ $company->address }}" class="form-control"
                            placeholder="Company Address">
                        @error('address')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
    </div>
</body>

</html>

 

If you submit the add or edit form blank. So the error message will be displayed with the help of the code given below:

@error('name')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror

 

Step 7 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/companies

Please Visit Our Main Blog : https://opencodesolution.com/

Search This Blog