teleren/devto huggingface dataset:
What is Custom Hook?
Tags: javascript, hook, react
Published: 2021-12-23 17:02:34


**What is Custom Hook?**
Custom Hook is a JavaScript function which we create by ourselves, when we want to share logic between other JavaScript functions. It allows you to reuse some piece of code in several parts of your app.
**When and How to Use**
When we want to share the logic between other components, we can extract it to a separate function. According to official documents, the custom hook has to:
start with the key word use
call other hooks
Because custom hook is a JS function, the Rules of Hooks apply to it as well. Those are:
Never call Hooks from inside a loop, condition or nested function
Hooks should sit at the top-level of your component
Only call Hooks from React functional components
Never call a Hook from a regular function
Hooks can call other Hooks
How to Create Custom Hook?
You create the hook same way as you create any JS function. Look at it as a refactoring of code into another function to make it reusable. It will speed up your productivity and save your time.
Let's consider the following example, where we have useEffect()hook which updates the document title:

```
import {useState, useEffect } from 'react';

    export const Counter=()=> {
      const [count, setCount] = useState(0);
      const incrementCount = () => setCount(count + 1);
      useEffect(() => {
        document.title = `You clicked ${count} times`
      });

      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={incrementCount}>ClickMe</button>
        </div>
      )
    }

```
What we want to do is to create a custom hook, which accepts a piece of text and updates the document title for us. Here is how we do that:

```
const useDocumentTitle = (title) => {
        useEffect(() => {
          document.title = title;
        }, [title])
      }
```

Our useDocumentHook() now accepts the string and calls useEffect() hook inside, which updates the document title with a given title, when the title was changed (we pass title as dependency here).
So our final code would look like this:

```
import { useState, useEffect } from "react";

const useDocumentTitle = (title) => {
  useEffect(() => {
    document.title = title;
  }, [title]);
};
```

```
export const Counter = () => {
  const [count, setCount] = useState(0);
  const incrementCount = () => setCount(count + 1);
  useDocumentTitle(`You clicked ${count} times`);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={incrementCount}>Click me</button>
    </div>
  );
};
```

And that is all, as simple as that :) In my next blog post I'll share 5 the most commonly used custom hooks, which make your development faster and easier.
CRUD Operation
Published: 2021-12-23 17:02:32

CRUD Operation

Working with CRUD operations we have to work with a database. CRUD operations are often used with SQL and also No SQL, a topic we've covered in depth. Since SQL is so prevalent in the development community, people should understand how CRUD operations work.

Definition of CRUD

The acronym CRUD refers to the four basic functions of persistent storage, including create, read, update, and delete. Also, each letter in the acronym can refer to all functions executed in relational database applications and mapped to a standard HTML method, SQL statement and NoSQL statement or DDS operation


Explaining CRUD Operations

When we need to keep the track of customer data,account, payment information, health
Data, and other records require data storage hardware and applications that provide persistent storage.There are many types of databases: hierarchical databases, graph databases, and object-oriented databases to name a few. The most commonly implemented type of database is a relational database, which consists of data tabled in rows and columns and connected to other tables with complementary information by a system of keywords that includes primary keys and foreign keys.And we use another database which is NoSQL database.


Four CRUD Operations Components Explained (NoSQL)

There are four CRUD operation components :

Create Operations

Read Operations

Update Operations

Delete Operations



Create Operations
Add new documents to a collection. If the collection does not exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
db.collection.insertOne() New in version 3.2
db.collection.insertMany() New in version 3.2
In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

 
Read Operations
Read Operation read the documents from a collection:
 
In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
Update Operations
In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
 
db.collection.updateOne() New in version 3.2
db.collection.updateMany() New in version 3.2
db.collection.replaceOne() New in version 3.2
 
You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations.

Delete Operations
Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection:
db.collection.deleteOne() New in version 3.2
db.collection.deleteMany() New in version 3.2
In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
You can specify criteria, or filters, that identify the documents to remove. These filters use the same syntax as read operations.
CRUD operation using node
Tags: javascript, react, node, mongodb
Published: 2021-12-23 17:01:00



**### CRUD Operations**

CRUD (Create, Read, Update, Delete) is an acronym for ways one can operate on stored data. It refers to operations performed in a database.


There is some HTTP method that is used to operate CRUD operation.

**POST Method :**

The POST method is used to create subordinate or new resources. When creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent, assigning an ID.

For example,

```
app.post('/products', async (req, res) => {
            const product = req.body;
            console.log(product)
            const result = await productsCollection.insertOne(product);
            res.json(result);
        });
```


**GET Method:**

The HTTP GET method is used to read a representation of a resource and returns a representation in XML or JSON and an HTTP response code of 200 (OK).

For example,

```
  app.get('/products', async (req, res) => {
            const cursor = productsCollection.find({})
            const products = await cursor.toArray();
            res.json(products);
        })
```

**PUT Method:**

PUT is used for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

For example,

```
 app.put('/users', async (req, res) => {
            const user = req.body;
            const filter = { email: user.email }
            const options = { upsert: true }
            const updateDoc = { $set: user }
            const result = await usersCollection.updateOne(filter, updateDoc, options)
            res.json(result);
        });
```

**PATCH Method:**

PATCH is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource.

For example,

```
PATCH /user/jthijssen HTTP/1.1
<user>
    <firstname>Joshua</firstname>
</user>
```

**DELETE Method:**

DELETE is used to delete a resource identified by a URI.

For example, 

```
 app.delete('/orders/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: ObjectId(id) }
            const result = await ordersCollection.deleteOne(query);
            res.json(result);
        })
```


To operate this operation, you have to must install,

> npm i cors

> npm i mongodb

> npm i express

> npm i dotenv

And must update in script object, 
like,

```
  "scripts": {
    "start": "node index.js",
    "start-dev": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }
```
About Middleware, differences between sql and nosql databases, API functions of Node.js & JWT.

Published: 2021-12-23 16:56:22


About Middleware,
Middleware comes in between your request and business logic. It is mainly used to capture logs and enable rate limit, routing, authentication, basically whatever that is not a part of business logic. There are third-party middleware also such as body-parser and you can write your own middleware for a specific use case.
 Differences between sql and nosql databases

SQL Database:
Relational Database
Vertically scalable
Table based Database
Predefined schema
Uses Structured Query Language

NoSQL Database:
Non Relational Database, Distributed Database
Horizontally scalable
Document based, graph based or key-value pair
Dynamic schema
Uses Unstructured Query Language


API functions of Node.js,

There are two types of API functions:
Asynchronous, non-blocking functions - mostly I/O operations which can be fork out of the main loop.
Synchronous, blocking functions - mostly operations that influence the process running in the main loop.



JSON Web Tokens,
JSON web token (JWT), pronounced "jot", is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. Again, JWT is a standard, meaning that all JWTs are tokens, but not all tokens are JWTs.

Because of its relatively small size, a JWT can be sent through a URL, through a POST parameter, or inside an HTTP header, and it is transmitted quickly. A JWT contains all the required information about an entity to avoid querying a database more than once. The recipient of a JWT also does not need to call a server to validate the token.

Use of JWT,
JWTs can be used in various ways:

Authentication: When a user successfully logs in using their credentials, an ID token is returned. According to the OpenID Connect (OIDC) specs, an ID token is always a JWT.

Authorization: Once a user is successfully logged in, an application may request to access routes, services, or resources (e.g., APIs) on behalf of that user. To do so, in every request, it must pass an Access Token, which may be in the form of a JWT. Single Sign-on (SSO) widely uses JWT because of the small overhead of the format, and its ability to easily be used across different domains.

Information Exchange: JWTs are a good way of securely transmitting information between parties because they can be signed, which means you can be sure that the senders are who they say they are. Additionally, the structure of a JWT allows you to verify that the content hasn't been tampered with.
Some-Backand-things
Tags: express, jwt, node, crud
Published: 2021-12-23 08:02:51

**_Explore Express: _**
Express.js is an open-source web application framework 
We can build a web application quickly and easily. Express js uses javascript that’s why it’s become easier for programmers and developers to build web applications. It is important to learn javascript and HTML to be able to use Express.js. 
Expree.js supports javascript which is a widely used language that is very easy to learn and is also supported everywhere.
Features of Express.js:
1.Faster Server side development, 2.Middleware, 3.Routing, 4. Templating, 5.Debugging

**_CRUD operation:  _**
**create-Operation: **In mongoDB when we can add new documents to a collection. If the collection does not exist, create operations also create the collection. We can insert one or many document 
i.db.collection.insertOne()
ii.db.collection.insertMany()

**Read Operation:** Read operations retrieve documents from a collection; i.e. query a collection for documents. We can find the document using the read operation.
db.users.find({})
We can find multiple or single element using the find operation. 

**Update Operations:** By using update operation we can update any document or replace any. We use these operation in mongodb for update 
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
**Delete Operation:**
 When we need to delete any document from the database we use delete operation to delete that element. 
db.collection.deleteOne()
db.collection.deleteMany()

**Node js:** Node.js is an open source server environment. It is free and it runs on different browsers. It also javascript.it uses asynchronous programming.It creates a dynamic page content.

**JWT Token: **JWT stands for JSON Web Token. We use this for  securely transmitting information between parties. Though it is digitally signed that’s why it is more than secure  and this information can be verified and trusted also.
 JWT authentication is a token-based stateless authentication mechanism. It is popularly used as a client-side-based stateless session, this means the server doesn’t have to completely rely on a database to save session information.
There are three parts of the jwt token header,payload,and signature.
Header
The header consists of two parts: 
The signing algorithm being used
The type of token, which is in this case mostly “JWT”
Example:
{ "alg": "HS256", "typ": "JWT" }
Payload
The payload usually contains the claims  and additional data like issuer, expiration time, and audience. 
Signature
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
Conditional rendering in React
Tags: react, javascript, tutorial, beginners
Published: 2021-12-23 16:55:36

To decide which UI elements to show or render in react is what we refer to as conditional rendering. This can be achieved by 3 ways which are helper functions, using ternary operators, and lastly by using simple if-else conditions in the render method. let us see some code examples to better understand these techniques.

**Conditional rendering using helper functions**
The idea is we abstract the logic from the render method and add it inside a function that will return some JSX or UI based on some conditions. 
Here is an example

```
class App extends React.Component{
  helperFunction = () => {
      return (
          <h2>
              I was returned from a helper function
          </h2>
      )
  }
  render() {
      return (
          <div>
              {this.helperFunction()}
          </div>
      )
  }
}
export default App;
```

```
class App extends React.Component {
  render() {

    const helper = () => {
      return <h2>I was returned from a helper function</h2>;
    };

    return <div>{helper()}</div>;
  }  
}
export default App;
```

**Using Ternary operators**
This is the most common way of handling conditional rendering in the react world to show a price of UI or to manipulate the values like adding classNames or showing values inside elements, this usually written inside the return method of components.
Let us see an example to understand this approach better

```
class App extends React.Component {
  
  state = {
    data:true
  }

  render() {

    return (
      <div>
        {
          this.state.data ? <p>Data is available</p> : <p>Sorry no data can be shown</p>
        }
      </div>
    )
  }
}

export default App;
```

**Use of If/Else conditions**
This is a very straight forward approach to decide which piece of UI or JSX we want to return to the user. see the below example to
understand this approach better.

```
class App extends React.Component {  
  state = {
    data:true
  }
  render() {
    if (this.state.data) { 
      return (<p>Data is available</p>)
    }
    else {
      return (<p>Sorry not data is available</p>)
    }    
  }
}
export default App;
```

if you like this article please do visit my blog here [www.uiuxtek.in](https://www.uiuxtek.in/)
JWT, Mongoose, CRUD Operations & Express
Published: 2021-12-23 16:47:56

**JWT**

JWT ot JSON Web Token is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. The tokens are signed either using a private secret or a public/private key. JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. WT, or JSON Web Token, is an open standard used to share security information between two parties — a client and a server. Each JWT contains encoded JSON objects, including a set of claims. JWTs are signed using a cryptographic algorithm to ensure that the claims cannot be altered after the token is issued.


**Mongoose**

Mongoose is a JavaScript object-oriented programming library that creates a connection between MongoDB and the Express web application framework. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. Mongoose is a Node.js-based Object Data Modeling (ODM) library for MongoDB.


**CRUD Operations**

In computer programming, create, read, update, and delete (CRUD) are the four basic operations of persistent storage. CRUD is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information using computer-based forms and reports. 


**Express**

Express.js, or simply Express, is a back end web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js.
Aggregation in node.js
Published: 2021-12-23 16:47:53

The aggregation framework permits you to investigate your information progressively. Utilizing the structure, you can make a total pipeline that comprises at least one phase. Each stage changes the reports and passes the result to the following stage.

Assuming you're acquainted with the Linux pipe ( | ), you can consider the collection pipeline fundamentally the same as the idea. Similarly, as result from one order is passed as a contribution to the following order when you use funneling, the yield from one phase is passed as a contribution to the following stage when you utilize the collection pipeline.

The conglomeration structure has an assortment of stages accessible for you to utilize. Today, we'll talk about the fundamentals of how to utilize $match, $group, $sort, and $limit. Note that the conglomeration structure has numerous other strong stages including $count, $geoNear, $graphLookup, $project, $unwind, and others.
Node CRUD Operations
Tags: node, react, mongodb, javascript
Published: 2021-12-23 16:44:42

**CRUD** (create, read, update, delete) is an acronym that refers to the four functions. There are different requests for each issue. For querying, we have GET requests, for sending data we have POST requests. These are called HTTP requests. They enable interactions between client and the server and work as a request-response protocol. 

![CRUD operation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqqreyzyfpztn8az974c.png)

`The HTTP requests are:`

**GET** is used to request data from a specified resource.

**POST** is used to send data to a server to create/update a resource.

**HEAD:** Same as GET, but it transfers the status line and the header section only.

**PUT:** Replaces all the current representations of the target resource with the uploaded content.

**DELETE:** Removes all the current representations of the target resource given by URI.

**CONNECT:** Establishes a tunnel to the server identified by a given URI.

**PATCH:** The PATCH method applies partial modifications to a resource

**`Route definition takes the following structure:`**

```
app.METHOD(PATH, HANDLER)
```

**Where:**

- `app` is an instance of express.
- `METHOD` is an HTTP request method, in lowercase.
- `PATH` is a path on the server. (URL path)
- `HANDLER` is the function executed when the route is matched. (Handler function)


**For GET method:**

```
app.get('/save', function(req, res) {
       // write query here
});
```

**For POST method:**

```
app.post('/save', function(req, res) {
       // write query here
});
```

**For PUT method:**

```
app.put('/save/:id', function(req, res) {
       // write query here
});
```


**For DELETE method:**

```
app.delete('/save/:id', function(req, res) {
       // write query here
});
```
Introduction to MongoDB
Published: 2021-12-23 16:43:02

MongoDB is an open source non-relational database that collects and stores data in the form of documents. These types of databases save a lot of functionality when offering horizontal scalability. It simplifies a developer's task by providing perseverance in data and increasing agility.

MongoDB saves JSON documents in the form of collections with dynamic schemas. It stores all the relevant information together which speeds up the query processing. As such, it also helps bridge the gap between key-value stores and relational databases.

Below I've listed some of the most interesting features of MongoDB:

Indexing: It uses indexes that help improve search performance.
Copy: MongoDB distributes data across different machines.
Ad-hoc queries: It indexes BSON documents and supports ad-hoc queries using a unique query language.
Skimless: This increases the flexibility of the data and does not require any scripts to modify or update the data.
Sharing: It uses sharding which simplifies the deployment of very large data sets and provides high throughput operations.
Now that you are familiar with MongoDB, let's move on to this Node.js MongoDB tutorial and see how easy it is to install MongoDB on a system.

Node.js MongoDB demo
Here I will create a CRUD application for conducting courses using Node.js and Express.js and use MongoDB to save data. In this application, I will take course details like name, ID, duration and fee as input. For this, I will create a few view files which will act as an interface. Then to manage the data, I also need a controller that will help to manipulate the data. Finally, I need a few model files to store the data. So basically, I'll follow an MVC pattern to develop this application. So, let's jump into development now.

Our application will have the following sequence:

- NodejsMongoDbDemo
- package.json
- script.js
- controllers
- courseController.js
- img
- logo.jpg
- models
- course.model.js
- mongodb.js
- views
- course
- courseAddEdit.hbs
- list.hbs
- layouts
- mainLayout.hbs