spycoding https://spycoding.com Learn Coding By Practicing Thu, 19 Nov 2020 12:43:05 +0000 en-US hourly 1 https://wordpress.org/?v=5.5.3 How to use Axios with ReactJs (Basic and Advanced concept) https://spycoding.com/how-to-use-axios-with-reactjs-basic-and-advanced-concept/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-use-axios-with-reactjs-basic-and-advanced-concept https://spycoding.com/how-to-use-axios-with-reactjs-basic-and-advanced-concept/#respond Thu, 19 Nov 2020 12:43:02 +0000 https://spycoding.com/?p=272 Read more How to use Axios with ReactJs (Basic and Advanced concept)]]> Hello friends, in this tutorial we are going to learn how to use Axios with reactjs effectively. We will see examples of Axios with reactjs.

INTRODUCTION

While working on web development, we all need to fetch the data, save the data, and perform any action. In that case, we need the way to call those services we may call that REST API. Reactjs Axios is promise based due to that it gives us the ability to take advantage of Javascript async and await functionality. It gives us more readable asynchronous code.

Prerequisites

  1. Node.js version 10.16.10 or later installed on your computer.
  2. Setup new Reactjs project. (How to setup Reactjs Project).
  3. Basic understanding of HTML and javascript

Why use Reactjs Axios?

Axios is promise-based. It also provides a more flexible and powerful feature set. These are the benefit of using rectjs Axios.

  1. It supports an older browser.
  2. It has built-in CSRF protection
  3. It has the ability to cancel the requests
  4. support for upload progress
  5. Request and response interception
  6.  It has optimal timeout property in the config. There we can set the number of milliseconds before the request is aborted. For example
axios({
  method: 'post',
  url: '/user/newUser',
  timeout: 5000,    // 4 seconds timeout
  data: {
    firstName: 'John',
    lastName: 'Loe'
  }
})
.then(response => {/* handle the response */})
.catch(error => console.error('timeout exceeded'))\

7. It has Automatic JSON data transformation
8. HTTP interceptors

axios.interceptors.request.use(config => {
  // log a message before any HTTP request is sent
  console.log('Request was sent');

  return config;
});

// sent a GET request
axios.get('https://api.github.com/users/abhayhk29')
  .then(response => {
    console.log(response.data);
  });

9. Simultaneous requests
10. It Has Better Error Handling

Step 1 – Adding Reactjs Axios to the Project

In this step, we will add Axios to our project. After installing the Axios, we need to import them into our project. We are going to use a demo API endpoint(JSON Placeholder). 

npm install axios

Step 2 – Creating a Folder structure

In this step, we will create a folder in that we will create respective files for the type of method(GET, Post, Put, Delete). For extracting the user detail, we will create GetUserDetail.js.

Step 3 – Get Method (GetUserDetail.js)

In this, we are fetching all data and showing it on the screen. We have user reactjs hooks for fetching the data by using axios.

import React, { useEffect, useState } from "react";
import Axios from 'axios';

function GetUserDetail() {

    const [userData, setUserData] = useState([]);

    useEffect(() => {
        Axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(function(res){
            setUserData(res.data);
        }).catch(function(err){
            console.log(err);
        })
    }, [])

    return (
        <div>
            {userData.map((user) => (
            <li key={user.id}>{user.title}</li>
          ))}
        </div>
    )
}
export default GetUserDetail;

We will see one more example of async and await. Here we will see how we are going to handle the async and await call in the reactjs. Async and wait are more readable as compare to classic promise based calls.

import React, { useEffect, useState } from "react";
import Axios from 'axios';
import { async } from "q";

function GetUserDetail() {

    const [userData, setUserData] = useState([]);

    const getUserDetail = async () => {
        try {
            const userData = await Axios.get('https://jsonplaceholder.typicode.com/posts');
            setUserData(userData.data);
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        getUserDetail();
    }, [])

    return (
        <div>
            {userData.map((user) => (
            <li key={user.id}>{user.title}</li>
          ))}
        </div>
    )
}
export default GetUserDetail;

Step 4 — Making a POST Request

In this step, we are going to use the POST method to create a new post. First, we will create the file CreateUserPost.js. In this section, we will use the reactjs hook method.

import React, { useState } from "react";
import Axios from "axios";

function CreateUserPost() {

    const [name, setName] = useState('');
    const handleChange = event => {
        setName(event.target.value);
    };

    const handleSubmit = event => {
        event.preventDefault();
        
        const userData = {
            name : name
        };

        Axios.post(`https://jsonplaceholder.typicode.com/posts`, {userData})
        .then(res => {
            console.log(res);
            alert(res.data.userData.name);
        }).catch(err => {
            console.log(err);
        })
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person Name:
                <input type="text" name="name" onChange={handleChange} />
            </label>
            <button type="submit">Add</button>
            </form>
        </div>
    )
}
export default CreateUserPost;

We will see the same example with the async and await method.

import React, { useState } from "react";
import Axios from "axios";

function CreateUserPost() {

    const [name, setName] = useState('');
    const handleChange = event => {
        setName(event.target.value);
    };

    const handleSubmit  = async (event) =>  {
        event.preventDefault();
        
        const userData = {
            name : name
        };

        try {
            const userDataRes = await Axios.post(`https://jsonplaceholder.typicode.com/posts`, {userData});
            if(userDataRes.status === 201){
                alert(userDataRes.data.userData.name);
            }else{
                alert('Please check your data carefully');
            }
        } catch (error) {
            console.log(error);
        }
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person Name:
                <input type="text" name="name" onChange={handleChange} />
            </label>
            <button type="submit">Add</button>
            </form>
        </div>
    )
}
export default CreateUserPost;

Step 5 — Making a DELETE Request

In this example, we see an example of the delete method. First, we will create a file DeleteUser.js. In that, we will create a form in which the user will provide an ID. By using that user will delete the user data. However, this is not a valid scenario in the real world. We have just taken an example to understand the Axios delete method.

import React, {useState} from 'react';
import axios from 'axios';

function DeleteUser() {

    const [id, setId] = useState('');

    const handleChange = event => {
        setId(event.target.value);
    };

    const handleSubmit = event => {
        event.preventDefault();
        axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`)
        .then(res => {
            console.log(res);
            console.log(res.data);
        }).catch(err => {
            console.log(err);
        })
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person ID:
                <input type="text" name="id" onChange={handleChange} />
            </label>
            <button type="submit">Delete</button>
            </form>
      </div>
    )
}

export default DeleteUser;

We will see same example with async and await functionality.

import React, {useState} from 'react';
import axios from 'axios';

function DeleteUserAsync() {
    const [id, setId] = useState('');

    const handleChange = event => {
        setId(event.target.value);
    };

    const handleSubmit =  async (event) => {
        event.preventDefault();

        try {
            const userData = await axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`);
            console.log(userData);
            if(userData.status === 200){
                alert('User deleted sucessfully');
            }else{
                alert('Please check your data carefully');
            }
        } catch (error) {
            
        }
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person ID:
                <input type="text" name="id" onChange={handleChange} />
            </label>
            <button type="submit">Delete</button>
            </form>
      </div>
    )
}

export default DeleteUserAsync;

Conclusion

In this article, we have seen an example of Axios with reactjs.
First, we have implemented the example with a simple method (Promise Based). After that, we have implemented the same code with javascript async and await functionalities. I hope we all have learned something from this article. Please provide your valuable feedback so that I can improve the quality of the tutorial. You can also share any new tutorial you want me to share. You can mail me at spycoding1@gmail.com.

]]>
https://spycoding.com/how-to-use-axios-with-reactjs-basic-and-advanced-concept/feed/ 0
A quick guide to creating charts in Reactjs using chart.js https://spycoding.com/a-quick-guide-to-creating-charts-in-reactjs-using-chart-js/?utm_source=rss&utm_medium=rss&utm_campaign=a-quick-guide-to-creating-charts-in-reactjs-using-chart-js https://spycoding.com/a-quick-guide-to-creating-charts-in-reactjs-using-chart-js/#comments Sun, 08 Nov 2020 15:56:04 +0000 https://spycoding.com/?p=241 Read more A quick guide to creating charts in Reactjs using chart.js]]> Hello friends, in this tutorial, we are going to implement the various chart using Reactjs. If we check npm, many packages allow us to create charts, graphs, etc. very quickly. In Reactjs, it makes things simpler. We are going to use chart.js and react-chartjs-2. Both packages need to be installed using npm.

In the first step, we will create a react js project using

npm create-react-app reactjsChart

In the second step we need to installed the chartjs module.

npm install chart.js react-chartjs-2

In the next step, we will create all the graphs one by one to demonstrate Reactjs charts’ power. First, we will create folder components in the src folder.

Part 1: Create Bar charts

For creating Bar first, we will need to create a file (BarChart.js) in the component folder.

// BarChart.js
import React, { useState, useEffect } from 'react';
import {Bar} from 'react-chartjs-2';

function BarChart() {

    const [data, setData] = useState({});

    useEffect(() => {
        setData(
          {
            labels: ['January', 'February', 'March',
                     'April', 'May'],
            datasets: [
              {
                label: 'Rainfall',
                backgroundColor: 'rgba(75,192,192,1)',
                borderColor: 'rgba(0,0,0,1)',
                borderWidth: 2,
                data: [65, 59, 80, 81, 56]
              }
            ]
          });
    }, [])


    return (
        <div>
            <Bar
            data={data}
            options={{
                title:{
                display:true,
                text:'Average Rainfall per month',
                fontSize:20
                },
                legend:{
                display:true,
                position:'right'
                }
            }}
        />
        </div>
    )
}

export default BarChart;
  1. First, we have imported the useState, useEffect from react. If you want to study more about the Reactjs hooks please visit this Reactjs Hooks. After that, we have imported the Bar from the ReactJs library.
  2. We have defined data using useState, and we have assigned a blank object as the initial value. In the second part, by using useEffect we have assigned a new value to the data. For example, if we want to fetch some data from the API. After that, we need to import this component into the app.js file.

Part 2: Create Line charts

For creating a Line graph first, we will need to create a file (LineGraph.js) in the component folder.

import React, {useState, useEffect} from 'react';
import {Line} from 'react-chartjs-2';

function LineGraph() {
    const [data, setData] = useState({});

    useEffect(() => {
        setData({
            labels: ['January', 'February', 'March',
                     'April', 'May'],
            datasets: [
              {
                label: 'Rainfall',
                fill: false,
                lineTension: 0.5,
                backgroundColor: 'rgba(75,192,192,1)',
                borderColor: 'rgba(0,0,0,1)',
                borderWidth: 2,
                data: [65, 59, 80, 81, 56]
              }
            ]
          });
    }, [])

    return (
        <div>
            <Line
                data={data}
                options={{
                    title:{
                    display:true,
                    text:'Average Rainfall per month',
                    fontSize:20
                    },
                    legend:{
                    display:true,
                    position:'right'
                    }
            }}
        />
        </div>
    )
}

export default LineGraph;
  1. The first step will be similar to the Bar graph. We need to import the necessary utility.
  2. In this step, we need to provide the default data set to display the line graph chart.

Part 3: Create Pie and Doughnut charts

For creating a Pie and Doughnut charts first, we will need to create a file (PieDoughnut.js) in the component folder.

import React, {useState, useEffect} from 'react';
import { Pie, Doughnut} from 'react-chartjs-2';

function PieChart() {

    const [data, setData] = useState({});

    useEffect(() => {
        setData({
            labels: ['America', 'Poland', 'Russia',
                     'France', 'Germany'],
            datasets: [
              {
                label: 'Average Population',
                backgroundColor: [
                  '#B21F00',
                  '#C9DE00',
                  '#2FDE00',
                  '#00A6B4',
                  '#6800B4'
                ],
                hoverBackgroundColor: [
                '#501800',
                '#4B5000',
                '#175000',
                '#003350',
                '#35014F'
                ],
                data: [600005, 500009, 800000, 800001, 500006]
              }
            ]
          });
    }, [])

    return (
        <div>
            <Pie
          data={data}
          options={{
            title:{
              display:true,
              text:'Average Population PIE Chart',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}
        />

        <Doughnut
          data={data}
          options={{
            title:{
              display:true,
              text:'Average Population Doughnut',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}
        />
        </div>
    )
}

export default PieChart;
  1. The first step will be similar to the Line graph. We need to import the necessary utility.
  2. We need to provide the default data set to display the Pie and doughnut graph chart in this step. Here we are going to display two chart Pie and doughnut with the same value.
  1. The first step will be similar to the Line graph. We need to import the necessary utility.
  2. We need to provide the default data set to display the Pie and doughnut graph chart in this step. Here we are going to display two chart Pie and doughnut with the same value.

Part 4: Grouped Bar Chart

The group bar charts are Bar charts in which multiple sets of the same data items are compared. For example rain last and this year. We can denote different colors to be specific. We can use both horizontal and vertical bar charts. For creating a group bar chart first, we will need to create a file (GroupChart.js) in the components folder.

import React, {useState, useEffect} from 'react';
import { Bar } from 'react-chartjs-2';

function GroupChart() {

    const [data, setData] = useState({});

    useEffect(() => {
        setData({
            labels: ['1', '2', '3', '4', '5', '6'],
            datasets: [
              {
                label: '# of Red Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: 'rgb(255, 99, 132)',
              },
              {
                label: '# of Blue Votes',
                data: [2, 3, 20, 5, 1, 4],
                backgroundColor: 'rgb(54, 162, 235)',
              },
              {
                label: '# of Green Votes',
                data: [3, 10, 13, 15, 22, 30],
                backgroundColor: 'rgb(75, 192, 192)',
              },
            ],
          });
    }, []);

    const options = {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true,
              },
            },
          ],
        },
      }


    return (
    <>
        <div className='header'>
        <h1 className='title'>Grouped Bar Chart</h1>
        </div>
        <Bar data={data} options={options} />
  </>
    )
}

export default GroupChart;
  1. In the first step, we will import the necessarily react module.
  2. After that, we will create a variable and set method by using reactjs useState hooks. In useEffect reactjs hook, we will load the data when the component is loaded. In this, we are going to display the difference between the three different sets.

Part 5: Stacked Bar Chart

A stacked bar graph extends the standard bar chart. It shows the comparisons between two or more categories. It divides the chart and compares the whole part. Each bar in the graph represents a fundamental full part.

import React, {useState, useEffect} from 'react';
import { Bar } from 'react-chartjs-2'

function StackedBar() {

    const [data, setData] = useState({});

    useEffect(() => {
        setData({
            labels: ['1', '2', '3', '4', '5', '6'],
            datasets: [
              {
                label: '# of Red Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: 'rgb(255, 99, 132)',
              },
              {
                label: '# of Blue Votes',
                data: [2, 3, 20, 5, 1, 4],
                backgroundColor: 'rgb(54, 162, 235)',
              },
              {
                label: '# of Green Votes',
                data: [3, 10, 13, 15, 22, 30],
                backgroundColor: 'rgb(75, 192, 192)',
              },
            ],
          });
    }, []);

    const options = {
          scales: {
            yAxes: [
              {
                stacked: true,
                ticks: {
                  beginAtZero: true,
                },
              },
            ],
            xAxes: [
              {
                stacked: true,
              },
            ],
          },
        };


    return (
    <>
        <div className='header'>
        <h1 className='title'>Stacked Bar Chart</h1>
        </div>
        <Bar data={data} options={options} />
  </>
    )
}

export default StackedBar;

Part 6: MultiType Chart

Multi-chart its allow us to plot data for multiple datasets into one graph. For example, plot the revenue collected each month for the last two years. It plots the high and low of multiple datasets while comparing the datasets.

import React, {useState, useEffect} from 'react';
import { Bar } from 'react-chartjs-2';

function MultiType() {

    const rand = () => Math.round(Math.random() * 20 - 10)

    const [data, setData] = useState({});

    useEffect(() => {
        setData({
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [
              {
                type: 'line',
                label: 'Dataset 1',
                borderColor: 'rgb(54, 162, 235)',
                borderWidth: 2,
                fill: false,
                data: [rand(), rand(), rand(), rand(), rand(), rand()],
              },
              {
                type: 'bar',
                label: 'Dataset 2',
                backgroundColor: 'rgb(255, 99, 132)',
                data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
                borderColor: 'white',
                borderWidth: 2,
              },
              {
                type: 'bar',
                label: 'Dataset 3',
                backgroundColor: 'rgb(75, 192, 192)',
                data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
              },
            ],
          });
    }, []);


    return (
        <div>
            <div className='header'>
            <h1 className='title'>Multi Type Chart</h1>
            </div>
            <Bar data={data} />
        </div>
    )
}

export default MultiType

Part 7: Root file of the Application (app.js)

It is the main root file for the application. In this, we will import all our components. I have just added one by one all the pieces(components). We can do styling than it will look better.

import React from 'react';
import './App.css';
import BarChart from './components/BarChart';
import LineGraph from './components/LineGraph';
import PieChart from './components/PieChart';
import GroupChart from './components/GroupChart';
import StackedBar from './components/StackedBar';
import MultiType from './components/MultiType';

function App() {
  return (
    <div className="App">
        <BarChart /> 
        <PieChart />
        <GroupChart />
        <StackedBar />
        <MultiType />
        <LineGraph /> 
    </div>
  );
}

export default App;

To run the application run this command

npm start

Conclusion

In this tutorial, we have tried to use the reactjs-chart to draw the simple bar charts. Thanks for the reading. Please give your feedback so that we can improve our tutorial.

]]>
https://spycoding.com/a-quick-guide-to-creating-charts-in-reactjs-using-chart-js/feed/ 3
How to use a Console log in Javascript to improve debugging? https://spycoding.com/how-to-use-a-console-log-in-javascript-to-improve-debugging/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-use-a-console-log-in-javascript-to-improve-debugging https://spycoding.com/how-to-use-a-console-log-in-javascript-to-improve-debugging/#respond Sun, 01 Nov 2020 16:21:10 +0000 https://spycoding.com/?p=213 Read more How to use a Console log in Javascript to improve debugging?]]> Hello friends, In this tutorial, we are going to learn about the Javascript Console. We will try to learn all the Javascript console concepts, which will help us debug our code more efficiently.

what is the javascript console?


In the web console, we use our console command to get the information exactly what is happening on our web page. We can also check what API call is going, security error, warnings, CSS issues, etc. Web console enables us to execute javascript on the web page. In javascript, the console provides us to debug the web page and find the error. It is an essential tool for web developers to debug the issues. There are many different types of console methods we will try to understand all the concepts one by one.

The following are the different types of console that we will be going to discuss in the tutorial.

  • log()
  • error()
  • warn()
  • clear()
  • time() and timeEnd()
  • table()
  • count()
  • group() and groupEnd()
  • custom console logs
  • trace()

1. Javascript console.log()

Javascript console.log is mainly used for printing the log or output to the web console. In Javascript console.log() we can pass any data type like string, array, object, boolean, etc.
Let me see show some examples.

console.log('Hi from console log'); // String
console.log(23232)// Number
console.log(true) // Boolean
console.log([1,2,4,5,7,9]) // Array
console.log({name:'John', age:32 }) // Object

console.log(), we can use mainly for the debugging process in our code. In one of our projects, we have created a module in which we have added the project’s logging process based on functionality. For example, in our application, there are twenty modules like authentication, authorization, cart, product page, etc. If there is some bug on the production, we need to start the specific log. By starting that log, we will see logs only for that module. It helps us to debug the bug fast. In the future, we are going to do this tutorial also.

In the console log, we can add style also to identify the warning, error, etc. Let see an example

console.log('%c Color ful logs! ', 'background: #222; color: #bada55');


The output will be like this. It has green text with a background color.

2. Javascript console.error()

Console.error() this method for writing error messages to the console. It is a very helpful tool for testing purpose.

console.error("You made a mistake in the code");

3.Javascript console.count()

The console.count() writes to the console the number of times the value is called. For example, take an example if we are iterating the users who have a salary more than a certain amount. By using the console.count() we can get how many times that condition has met.

for(var i = 0; i < 7; i++){
    console.count();
}
VM580:2 default: 1
VM580:2 default: 2
VM580:2 default: 3
VM580:2 default: 4
VM580:2 default: 5
VM580:2 default: 6

We can see that the default added label is “default” in the output. If we want to change, we have the option to change it. We have replaced the default with “Counter countdown.”

for(var i = 0; i < 7; i++){
    console.count('Counter countdown');
}
VM628:2 Counter countdown: 1
VM628:2 Counter countdown: 2
VM628:2 Counter countdown: 3
VM628:2 Counter countdown: 4
VM628:2 Counter countdown: 5
VM628:2 Counter countdown: 6
VM628:2 Counter countdown: 7

4. Javascript group() and groupEnd()

The console.group() methods allow us to group the console.log() in a separate block. It will help us to get the idea of a log belongs to a specific group. Console .groupEnd() is used to end that specific groups of logs. Let see the examples

console.group()
console.log('State 1 phase 1');
console.log('State 2 phase 2');
console.log('State 3 phase 3');
console.log('State 4 phase 4');
console.log('State End phase End');
console.groupEnd();
console.log('outside the group');

The output for the console.group() and console.groupEnd() will look like the above image. We can see that console.log() has been grouped and ended just above the console.groupEnd(). It has been advantageous while debugging the issue in our application.

5. Javascript console.info()

The console.info() methods use to output info messages to the console. This method accepts only a single parameter message, which is mandatory and used to output the web console information.

console.info('In side the information')

VM997:1 In side the information

6. Javascript console.table()

The console.table() method is used to output the data in table format in the console view. The first parameter is required and must an array or an object holding the data. The console.table() gives us the ability to generate a table inside a web console.

console.table([
  {
    first: 'John',
    last: 'Loe',
  },
  {
    first: 'Abhishek',
    last: 'Tripathi',
    birthday: '18930113',
  },
  {
    first: 'Henri',
    last: 'Paul',
  }
]);

It will all the provided data into the tabular format in the web console as given in the image.

7. Javascript console.time() and console.timeEnd()

We have seen many times that sometimes we need how much time is elapsed to complete the process. For that reason, console.time()
and console.timeEnd() is very useful.

In a nutshell, we can say that console.time() will start the timer.
console .timeEnd() will stop the timer and give the time in which the process has completed. This method allows you to time certain operations in your code for testing purposes. The result will be in the milliseconds and might be different each time, depending on the page’s execution.

console.time("test for start and end time");
for (i = 0; i < 1000000; i++) {
  // some code
}
console.timeEnd("test for start and end time");

output:

VM1096:5 test for start and end time: 4.4619140625 ms

8. Javascript console.trace()

The console.trace is very useful in debugging regarding the execution path. Primarily the console.trace() give us the information on hows the code ended at a specific time(point).

const firstSection = () => { secondSection(); };
const secondSection = () => { thirdSection(); };
const thirdSection = () => { fourthSection(); };
const fourthSection = () => { console.trace(); };
firstSection();

In the given, we have seen that there are four functions are defined. They are calling each other the first function call the second likewise. In the fourth function, we have added the console.trace() method. It will output the flow of the execution.

9. Javascript console.warn()

The console.warn() method writes a warning to the web console. It accepts a single parameter message, which is mandatory.

console.warn('Its warning');

10. What is the difference between the Javascript console.log and console.dir() ?

The console.log() method used to display the string representation of any object passed to it. The console.dir() displays an interactive list of the properties. The output is presented as a hierarchical listing.

var a = {
    name: 'John',
    lastName: 'Doe',
    age: '32'
}

console.dir(a);

console.log(a);

Conclusion

As we have seen, the Javascript console provides us a very efficient tool to debug our code. We can get the code execution time of the function by using console.time(). We can style the log to differentiate the log. I hope you have all find this tutorial useful. 

]]>
https://spycoding.com/how-to-use-a-console-log-in-javascript-to-improve-debugging/feed/ 0
How to Create a Simple Restful API using NodeJs, ExpressJs, And MongoDB https://spycoding.com/how-to-create-a-simple-restful-api-using-nodejs-expressjs-and-mongodb/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-create-a-simple-restful-api-using-nodejs-expressjs-and-mongodb https://spycoding.com/how-to-create-a-simple-restful-api-using-nodejs-expressjs-and-mongodb/#comments Sun, 25 Oct 2020 12:35:14 +0000 https://spycoding.com/?p=179 Read more How to Create a Simple Restful API using NodeJs, ExpressJs, And MongoDB]]> In this article, we are going to create Rest API using NodeJs, Express, and MongoDB. In the first phase, we will describe what do we mean by REST API.

Definition of Restful API

REST is an acronym for “REpresentational State Transfer”. Like any other architectural style, Rest also has its guiding protocol, which consists of SIX guidings constraints.

Guiding principles of REST

  1. Stateless – Each request from the client should contain all necessary information which is essential to understand the request.
  2. Cacheable – If the user request is implicitly or explicitly marked as cacheable. Then it has the right to reuse the response data for equivalent recommendations(request).
  3. Client-server – By using the REST API, we have separated the client and server concepts. It will improve the scalability of application and reusability.
  4. User Interface – The overall system architecture is improved (Simplified) by approaching the REST API. 

    For more information, you can visit.

In this article, we are going to create API to demonstrate the CRUD operation. We will use NodeJs, Express and MongoDB.

Step 1: Initialization of project

First, we need to create a project folder. After making the project folder, we need to initialize the application. We need to create the package.json file which will hold all the metadata for the applications. We need to execute the following command

npm init -y

The above-given command will create a package.json file

Step 2: Install the necessary

In this section, we will install all the required dependencies of the project. We will run the following command to install the dependencies

touch app.js
npm install express mongoose body-parser --save

Using the given commands we have created a file app.js which will be the main entry point of the application. After that, we have installed the few dependencies that are essential to run our application.

These are the dependencies.

  1. MongoDB – This module is used to communicate to the MongoDB database.
    We are using the mongoose npm package to interact with the MongoDB database. We are going to connect to the MongoDB database using the free service of MongoDB official website(www.mongodb.com).
  2. Express – NodeJs framework
  3. Body Parser – It will allow us to handle the request body with express.

Step 3: Setup the database

Login to www.mongodb.com there we can create our account fo free. We will use this service to connect to the MongoDB database. After login, we need to set up our default language we can change it later as per our requirement. I have set Javascript as per now because we are using NodeJs.

After selecting the default language, we need to continue. Next step, is to create the shared cluster it is absolutely free.

Next, we need to select the cloud server and region. I have chosen AWS and the nearest data center as per your current location. It will take some time to complete the process. Next, we need to create the user and collection name. The user is used to connecting to the database from the application.

Next, step is to click on the connect option that you got on the next page. There we need to add the username and password that we will use to connect to the application. Please store that username and password we will need that while connecting to the application. After that we need to choose a connection method.

In that, we need to choose an option for the connection method. We will opt for “Connect your application.”

After selecting the option “Connect your application.” we will get a window there, we need to copy the connection string. In the copy connection string, replace username, password, and database name as we have created.

Step 4: Implementing the CRUD functionality using NodeJs, Express and MongoDB

In earlier steps, we have initialized the application and created the basic structure of the project.
We are going to store the user information for demonstrating the CRUD functionality using NodeJs, Express and MongoDB. We are going to store the following details for the user.

  1. Username
  2. Email
  3. Contact
  4. City
  5. Gender

Let’s structure our project first app.js will be our entry file into the application. We will divide code into the three main parts in a big project we need to go into the more dipper level. The folder structure will look like this, We have created a separate folder structure for the components in the project like the controller, model, and routes.

  1. Model: In this, we will define the structure of the collection that we are going to create.
  2. Controller: In this, we will perform the application functionality.
  3. Routes: In this, we will make the route by which the user will interact with the API.

We will start with the Model file that is in the model folder i.e user.js.
In that first, we have required the mongoose which we have installed at the beginning of the project. It will use to initialize the model for the collection. In this, we have defined the value that we want to store in the database like username, city, email, contact and gender. 

//mongoose to connect to the MongoDb 
const mongoose = require('mongoose');

// simple Schema
const UserSchemaInfo = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 4,
        maxlength: 60
    },
    email: {
        type: String,
        required: true,
        minlength: 6,
        maxlength:255,
        unique: true
    },
    contact: {
        type: String,
        required: true,
        minlength: 11,
        maxlength:100
    },
    city: {
        type: String,
        minlength: 6,
        maxlength:100
    },
    gender: String,
    create_date:{
        type:Date,
        default: Date.now
    }
});

const Userinfo = mongoose.model('User', UserSchemaInfo);
exports.UserInfo = Userinfo;

Second Part will be the controller in this file we have defined all the operation that we are going to perform on the user collection, i.e. Create, Read, Update and delete.

In this first, we have imported the required model file. After that first operation “exports.index” in this, we have returned all the saved user in the database. In the second operation “exports.userNew” we have created the new user. Here we are merely inserting the data. We can check like the same user cannot be added twice etc. as per our requirement.

In the third function, we are finding the user by the user id and returning the fetched user.

In the fourth function, we are deleting the user by the provided user id.

In the last function, we are updating the user information provided by the input.

// user controller we will here perform all the action 

// import the the cuser model

const { UserInfo } = require('../model/user');


// API to handle the Index Action or we can say that 
exports.index = function ( req, res ) {
    UserInfo.find(function (err, users){
        if(err){
            res.json({
                status: 'error',
                message: err
            })
        }
        res.json({
            status:"success",
            message: 'User information sucessfully',
            data: users
        });
    });
};

// API to handle the creation of the user 

exports.userNew = function (req, res) {
    var user = new UserInfo();
    user.name = req.body.name;
    user.email = req.body.email;
    user.contact = req.body.contact;
    user.city = req.body.city;
    user.gender = req.body.gender;

    // use to save the user in the databases
    user.save( function (err) { 
        if(err){
            res.json({
                status: 'error',
                message: err
            })
        }
        // if there is no error return the user detail
        res.json({
            message: "User created successfully",
            data: user
        });
    })
};

// to retrieve the user info based on the user ID
exports.userInfoById = function(req, res){
    UserInfo.findById(req.params.user_id, function(err, userData){
        if (err){
            res.json({
                status: 'User not found',
                message: err
            });
        }
        res.json({
            message: "user info details by id",
            data: userData
        });
    });
};

// Delete the user
exports.deleteUser = function (req, res){
    UserInfo.remove({
        _id: req.params.user_id
    }, function (err, user) {
        if (err){
            // if there is no user found to delete the user
            res.json({
                status: 'User is not deleted',
                message: err
            });
        }

        // if user is deleted successfully
        res.json({
            message:"User deleted successfully",
            data: user
        });
    });
};

// Function to update the user
exports.updateUser = function (req,res){
    // first we will find the user existor not if user exist we will update user 
    UserInfo.findById(req.params.user_id, function(err, user) {
        if (err){
            res.json({
                status: 'User not found',
                message: err
            });
        }

        user.name = req.body.name;
        user.email = req.body.email;
        user.contact = req.body.contact;
        user.city = req.body.city;
        user.gender = req.body.gender;

        user.save(function (err) {
            if(err){
                res.json({
                    status: 'User not updated',
                    message: err
                });
            }

            res.json({
                message: 'User updated successfully',
                data: user
            });
        });
    });
};

The third part will be the routes in that file. We will define how the user will interact with the application by using that endpoint.

We will implement the following endpoints

  • GET /api/userInfo/users list all contacts
  • POST /api/userInfo/user create new contact
  • GET /api/userInfo/user/{user_id} retrieve a single contact
  • PUT /api/userInfo/user/{user_id} update a single contact
  • DELETE /api/userInfo/user/user_id} delete a single contact
// intialize the express router for the user
const router = require('express').Router();

// default API response

router.get('/', function(req, res) {
    res.json({
        status: 'API is initialize the working',
        message: 'user default REST API'
    });
});

// import the user controller 
const userController = require('../controller/userController');

// User routes
router.route('/users')
    .get(userController.index)
    .post(userController.userNew);


    // routes to get the user info based on the user id


router.route('/user/:user_id')
    .get(userController.userInfoById)
    .patch(userController.updateUser)
    .put(userController.updateUser)
    .delete(userController.deleteUser);
    
    
// exporting the user API routes
module.exports = router;    

The last file will be our entry file to the application, i.e. app.js. In this firstly, we have required the express, i.e. node web framework. Second is body-parser it is node js middleware to handle, available under the req.body property. If you want to learn more about middleware in the NodeJs, please visit NodeJs Middleware. After that, we have required our routes file. We have connected to our database. We have added the routes for the user. By this, we have completed our implementation. Let’s try the different routes to perform CRUD operations.

// import the express
const express = require("express");
// import the body Parser
const bodyParser = require('body-parser');
// import the mongoose to connect to the MongoDB
const mongoose = require("mongoose");
// import the user routes
const userRoutes = require("./routes/userRoutes");

const port = process.env.PORT || 9001;
const app = express();

// configure bodyparser to handle the post request
app.use(bodyParser.urlencoded({
    extended:true
}));

// use body parser
app.use(bodyParser.json());



//connection to the moongoose 
const connection_url = 'mongodb+srv://adminTest:admin@123@cluster0.qutfh.mongodb.net/userInfo?retryWrites=true&w=majority'
mongoose.connect(connection_url, {
    useCreateIndex:true,
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => console.log('connected to MongoDb'))
.catch(err => console.error("could not connect to mongodb"));

// URL for the default URL
app.get('/', (req,res) => res.send(' API request with express'));

// adding the route for User
app.use("/api/userInfo", userRoutes);

app.listen(port, () => 
    console.log(`listening on port ${port}`));

Now we will run the application by executing this command in the terminal

node app.js

Now we will use all the routes that we have created (CRUD).

  1. Create . In this we will create a new user by using PostMan. Our URL will be “localhost:9001/api/userInfo/users”. The method will be POST for creation operation.

2. Read: We can fetch one user detail by user_id or we can get all the user’s information lets to try this URL “localhost:9001/api/userInfo/users”. The method will be ‘GET’ for retrieving the information for the database.

3. Update: In this we will update the user information. URL will be “localhost:9001/api/userInfo/user/5f94f0be5c89ef36023fba28”. The method will be “PUT” for updating the user in the database.

4. Delete: In this section, we will delete the user by the user_id provide by the user. URL will be
“localhost:9001/api/userInfo/user/5f94f0e45c89ef36023fba29”. The method will be “DELETE”
for deleting the user information from the database.

Conclusion

In this tutorial, we are trying to learn and develop a custom API and connect to the MongoDB and fetch or manipulate the data. However, this is a very basic project to understand the CRUD functionality. You can add more features like security, validation of data. Please try in your side if you find any problem I am here to help you please free to connect me.

]]>
https://spycoding.com/how-to-create-a-simple-restful-api-using-nodejs-expressjs-and-mongodb/feed/ 1
ReactJs Tutorial: How to use ReactJs Hooks (useState, useEffect) https://spycoding.com/reactjs-tutorial-how-to-use-reactjs-hooks-usestate-useeffect/?utm_source=rss&utm_medium=rss&utm_campaign=reactjs-tutorial-how-to-use-reactjs-hooks-usestate-useeffect https://spycoding.com/reactjs-tutorial-how-to-use-reactjs-hooks-usestate-useeffect/#comments Mon, 12 Oct 2020 16:34:53 +0000 https://spycoding.com/?p=145 Read more ReactJs Tutorial: How to use ReactJs Hooks (useState, useEffect)]]> In react 16.8, it came with a gift to all React developers, i.e., Reactjs hooks. It launched at the React conference in October 2018. In Reactjs hooks, we can use all other ReactJs features without using class. It means we can use state and other React features without writing a class.

It is a fundamental change in which we can move to functional components. It doesn’t mean we should not write previous class components. It’s 100% backward compatible.

At React Conference 2018, Sophie Alpert and Dan Abramov introduced Hooks, you can watch the video introduction below:

What motivated to ReactJs team to introduce this new concept “hooks.”. There were some issues that the ReactJS team decided to introduce this concept. We will briefly describe those concepts lets check those.

1. What is a React Hook?

Hooks are functions that let you “Hook” into the React state and lifecycle features from function components without using class. Hooks don’t work inside the classes. There is no need to rewrite the old react classes. But surely you can use hooks in new code.

Reacts provides few built-in hooks like useState, useEffect, etc. In this article, we will try to understand those few inbuilt hooks.

There are some rules for using the Hooks in ReactJs.

  1. Call Hooks at the top level. Please don’t call reactjs hooks inside the loops, conditions, etc.
  2. Call Hooks from React function components. Please don’t call it from regular Javascript functions.

1. useState Hook

A hook is a particular function that let you hook into the react features. useState is a hook that lets you add React state to the functional components without using classes.

Let’s assume that you are writing a function component, and later you realize that you need to add some state to it. Earlier, we need to convert it to a call. There we can manage the state. After introducing the hooks, we can manage it into the functional components by using the “useStae” hooks.

First, we will see in class how we are managing the state. In class, first, we need to add constructors in the class. After that, we need to initialize the count in this.state to zero( count : 0).
On rendering the component, the initial value of count will be 0.

import React, { Component } from 'react'

class ClassCounter extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             count:0
        }
    }

Now we will see the example using functional components. In this functional component, we have
initialize the state by using the react hook. First, we need to import useState. In functional components, we don’t need to use the “this” variable. There we need to call useState directly inside the functional components.

import React, {useState} from 'react';

function DataFetchingOne() {

    const [loading, setLoading] = useState(true); 
// initial value to true

What does calling useState do?
It declares the state variable. In our case, the count is the variable. Another value is a function to change the count variable.

What do we need to pass to useState as an argument?
In useState we need the only argument need to pass in the initial state. It does’t need to be an object as we do in classes. In our example, we need a number for how many times the user has clicked on the button. We have passed the initial value as 0—the second part is to set a new value for the count variable. If we need two different values in state, we need to call useState() twice.

How to read state in the hooks

In functional components, we can call value directly.

<div> Count - {count}</div>

How to Update State in the functional hooks

First, we will see the example in the class component

 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
  </button>

In functional components, we already have setCount and count as variables. So there we need to call the setCount function.

<button onClick={() => setCount(count + 1)}>
    Click me
  </button>

Example of ReactJs Hooks Snippet using functional components

import React, { 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>
  );
}

Example of above example using class snippet

import React, { Component } from 'react';

class Counter extends Component {

    constructor(props) {
        super(props)
    
        this.state = {
             count:0
        }
    }

    increment(){
        this.setState({
            count: this.state.count + 1
        }, ()=> {
            console.log(this.state.count);
        });
    }
    
    render() {
        return (
            <div>
                <div>count - {this.state.count}</div>
                <button onClick={() => this.increment()}>Increment</button>
            </div>
        )
    }
}

export default Counter;

2. useEffect Hook

useEffect is short for ‘use side effect’. Effects mean when our application reacts with the outside world, like calling an API. It allows us to run a function when there are some changes in the application.

Suppose you have an understanding or familiar with React class lifecycle methods. You can easily understand the useEffect. We can think of useEffect as componentDidMount, componentDidUpdate, and componentWillUnmount like class components. To use useEffect first, we need to import it.

import React, { useEffect } from 'react';

The useEffect() functions to run when the component is first rendered, and on every subsequent, changes it will update. React will first update the DOM. After that, it will call the function passed to useEffect. The useEffect() functions to run when the component is first rendered, and on every subsequent, changes it will update. React will first update the DOM. After that, it will call the function passed to useEffect without blocking the UI rendering. It will help us to make out apps feel faster. We can add multiple useEffect in a single component. Let’s see an example.

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

function HookMouse() {

    const [x, setX] = useState(0);
    const [y, setY] = useState(0);

    const logMousePosition = e => {
        console.log('Mouse Event');
        setX(e.clientX);
        setY(e.clientY);
    }

    useEffect(() => {
        console.log('Use Effect Called');
        window.addEventListener('mousemove', logMousePosition);
    })

    return (
        <div>
            Hooks X - {x} Y - {y}
        </div>
    )
}

export default HookMouse;

This example is similar to componentDidUpdate lifecycle of a stateful component. Now we will implement all the lifecycle components life cycle in functional components as they are implemented in the Class components.

  1. How to make it work like componentDidMount

Suppose we will pass an empty array in useEffect function as the second parameter. Then it will behave like componentDidMount. Let see an example

const  SpyCoding = (props) => {
   useEffect( () => {
      console.log(‘hello from useEffect call componentDidMount’);
      setTimeout( ()=>{ alert(‘hello Reactjs Hooks’); }, 2000);
   }, [] );
}

We can pass the second argument in the userEffect function. If there are any changes, then only that specific userEffect function will execute. The second argument is an array means we can pass multiple elements inside that array. Let see an example for this

useEffect((props) => {
        Axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
        .then(res => {
            console.log(res);
            // setPosts(res.data);
            setPost(res.data);
        })
        .catch(err => {
            console.log(err)
        })
    }, [props.id])

If there is any changes in the “id” props the userEffect function will be executed.

2. How to do cleanup work in functional component (componentWillUnmount)

Inside useEffect if we will add a return statement at the end of the useEffect function. That return function does the cleanup work. It similar to componentWillUnmount. Let see an example

const [count, setCount] = useState(0);

const tick = () => {
   setCount( prevCount => prevCount + 1);
 } 

useEffect(() => {
        const interval = setInterval(tick, 1000);
        return () => {
            clearInterval(interval);
        }
    },[count])

In this example, the count is increasing every second. When we remove that component, the return function will execute the return function. In that, it will clear the setInterval.

If you have used class components with lifecycle methods, we can easily understand that how much it has become optimized by using reactjs hooks. Earlier, we need to use _prevProps or _prevState and compare it with the current. If they do not match, we execute the functionality. Now, in hooks, we need to pass the extra parameter. That will ensure that the hook is run only when the state gets change.

Conclusion

Hopefully, we have learned some basic concepts of the reactjs hooks. If we carefully understand the concepts, we can conclude that hooks are designed to solve most of the problem that class components suffer from. It has been recommended that you gradually shift towards the reactjs hooks.

]]>
https://spycoding.com/reactjs-tutorial-how-to-use-reactjs-hooks-usestate-useeffect/feed/ 2
A React.js tutorial for beginners https://spycoding.com/a-react-js-tutorial-for-beginners/?utm_source=rss&utm_medium=rss&utm_campaign=a-react-js-tutorial-for-beginners Sat, 26 Sep 2020 18:06:46 +0000 https://spycoding.com/?p=118 Read more A React.js tutorial for beginners]]> Hello friends, in this article, we will learn about the basic concept of the Reactjs. We will start with the fundamental idea in this tutorial. Further, as we progress, I will add some more interactive tutorials with practicals and advanced concepts.

Introduction to Reactjs

ReactJS is a javascript library created and maintained by Facebook. ReactJS is an open-source and component-based front end library responsible for the view player of the application. Its declarative, efficient, and flexible Javascript library for building user interfaces. A react application is consists of multiple components. Each component was responsible for rendering a small piece of HTML. Components can be nested with other parts to allow the complex application to be built from simple blocks of the component.

If we see a modern web application, there are many famous web applications based on reactJs. Some of the renowned web applications are as given below

  1. Facebook
  2. Instagram
  3. Netflix
  4. New York Times
  5. WhatsApp
  6. Khan Academy

In this article, we are going to cover the below concept

  1. create react app
  2. The folder structure of the reactjs application
  3. Components in the ReactJS and Props
  4. React JSX

Step 1 : Create ReactJS APP

First, we need to install the create-react-app by running this command in our terminal:

C:\Users/admin>npm install -g create-react-app

After installing this create-react-app we can create our basic react application. In your terminal, run this command

C:\Users\admin>npx create-react-app firstReactApp

The create-react-app will set up everything we need to run a RactJS application. After that just move to our created application

C:\Users\admin>cd firstReactApp

After this, we need to run the application by executing the given command in the terminal.

C:\Users\admin\firstReactApp>npm start

The application will run on the http://localhost:3000

Step 2: The folder structure of the ReactJS application

Officially React doesn’t have any predefined structure. But there are few common approaches that developers adopt.

  1. Grouping by ( features or routes )

In this file is arranged as grouped by feature or route.

common/
  userProfile.js
  userProfile.css
  util.js
  util.test.js
feed/
  index.js
  Feed.js
  Feed.css
  FeedStory.js
  FeedStory.test.js
  FeedAPI.js
profile/
  index.js
  Profile.js
  ProfileHeader.js
  ProfileHeader.css
  ProfileAPI.js

2. Group By File Type

Another popular way to structure the projects into group similar files together

API
  api.js
  util.js
components/
  Avatar.js
  Avatar.css
  Feed.js
  Feed.css  

For more information visit this URL.

Step 3: Components in the ReactJS and Props

Components split our UI into many small independent, reusable pieces. We can take this example; we have a web application to divide it in a broader way like that header, side panel, content, and footer. These all are components of that web APP but in a significantly broader way.
We can divide each UI into a tiny independent component.

For example, we can create a component in which we are just showing a success message. That component we can use in all of the Project we just need to import that component. In Reactjs, components are conceptually are like Javascript functions. They accept the parameter (called “props”) and return React elements. These elements will describe what will appear on the screen.

There are two types of components in the ReactJs

  1. Functional Components
  2. Class componens

A. Functional Components

Functional components are simple Javascript function which accepts the parameter and returns the result. This function is a valid React functional component because it accepts a single parameter, i.e., “props” it contains the object argument which contains the provided data. After processing the data, it returns a React element. Such components we called it Functional components.

function AddUser(props) {
  return <h1>Hello, new user {props.name}</h1>;
}

B. Class Components

When we use the ES6 class to define the component, then it is called a class component

class AddUser extends React.Component {
  render() {
    return <h1>Hello, new user, {this.props.name}</h1>;
  }
}

Example of Class component

class UserInfo extends React.Component {
  render() {
    return <h2>My Email id is{this.props.user.email}!</h2>;
  }
}

class User extends React.Component {
  render() {
    const userInfo = {name: "Neil", email: "neil@spycoding.com"};
    return (
      <div>
      <h1>Email id of login user?</h1>
      <Car UserInfo={userInfo} />
      </div>
    );
  }
}

ReactDOM.render(<User />, document.getElementById('root'));
 
 
 

C. props

Mostly, props are passed to components by using HTML attributes. React props are like arguments in the Javascript functions and attributes in the HTML. Take an example; we are passing name like Albert Einstein in the component as follow:-

const scientist = <ScientistName name="Albert Einstein" />;

The functional and class components receive the argument as a props object:

Example

Use the scientist attribute in the component:

class ScientistName extends React.Component {
  render() {
    return <h2>I am a {this.props.name}!</h2>;
  }

We have created one component in which we just need to pass the scientist’s name. It will work for any number of the scientist name. We can create as many small components, and we need to import and use that component. Take another example we have created a component “Button” in which we can pass color, class name, etc. as props. Wherever we need Button, we just need to import it and pass the attribute.

Differences between functional and class-Components

Functional ComponentsClass Components
Functional components are plain JavaScript function which accepts parameter(props) as an argument and return(React Element).A class component is an ES6 based class in this; you need to extend from the React. It requires more code, but it also gives you more benefits.
Functional components are referred to as “dumb” or stateless because they accept data and display them is some form. Mainly they are responsible for rendering the UI.Class components called “smart” or “stateful” components as they tend to implement logic.
No lifecycle methods such as componentDidMount cannot be used in the functional components.In the Class component, we can use React lifecycle methods.
In functional components, props can be used directly as {props.name}.In class components. props can be used as {this.props.name}

Step 4: React JSX

JSX abbreviate for JavaScript XML. Like in the XML, we can create our tags similarly. Due to JSX, it allows us to write HTML in react. Due to this, it became easier to write and add HTML to React. JSX allow us to write HTML elements in javascript and easily place them in the DOM without any createElement() / appendChild() functions. JSX will throw an error if the HTML is not proper. It also throws an error if the Parent element is missed.

Let’s take an example first with JSX and second without the JSX.

Example 1 (with JSX)

const element = <h1>Hope for Best!</h1>;

ReactDOM.render(element, document.getElementById('root'));

Example 2 (without JSX)

const element = React.createElement('h1', {}, 'Hope for Best!!');

ReactDOM.render(element, document.getElementById('root'));

In JSX, we can use expression also. JavaScript function calls and evaluates to JavaScript objects.

function getUserInfo(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;  }
  return <h1>Hello, Stranger.</h1>;}
}

When we are embedding a JavaScript expression in an attribute, we should use quotes for string values or curly braces for the expressions. We shouldn’t use both in the same attribute.

Conclusion

I hope you all like this basic subjective tutorial. I have tried to explain the basic ReactJs concepts. From the next tutorial, we will like to implement some basic react tutorial. In the tutorial, there is more chance to clear our doubts.

]]>
Implementation of authentication and authorization in Node Js https://spycoding.com/implementation-of-authentication-and-authorization-in-node-js/?utm_source=rss&utm_medium=rss&utm_campaign=implementation-of-authentication-and-authorization-in-node-js Sat, 19 Sep 2020 17:03:28 +0000 https://spycoding.com/?p=90 Read more Implementation of authentication and authorization in Node Js]]> In this article, we are going to learn how to implement Authentication and Authorization for our Node server. In the first part, we will try to understand the basic definition of authentication and authorization.

Introduction

Firstly, we will try to understand what does mean by authentication. Authentication means to recognize the proper user should enter the system or any infrastructure which have any sensitive data. A basic example is Facebook login; we enter our credentials consist of usernames and passwords. If we have entered the correct credentials, we can login to our system. There are different types of authentication processes. Following are some of the authentication process

1. Password-based authentication. (simple authentication based on the username and password)

2. Multi-factor authentication (Based on some code generated such as PIN, OTP, etc.)

3. Biometric authentication (Such as retina based, FingerPrint scanners, face-based recognization, etc.)

4.Token-based authentication (Many companies use this type of authentication to login into there system. These token are mainly time-based they will expire after a specific time)

5. Certificate-based authentication( Digital certificate to enter to the system)

There are many more types of authentication, but these are all basic fundamental types of login.

Now we will try to understand the meaning of authorization.

Authorization is the mechanism to determine the access level of the user. The type of action user can act depending on the status of the privileges to that user.
For example, an accountant will only allow checking the finance part. Admin has access to fit all the operations into the system.

IMPLEMENTATION OF AUTHENTICATION AND AUTHORIZATION IN NODE.JS

We will make an API using that new user registration can be done. Based on the user result will show. For example, I have created a user that has a role user. Based on that role we will output the result. If the user has a role admin the output will be different.

For that we will also use JWT(JSON web token). Following are the dependencies

  1. express — web framework
  2. joi — validation function
  3. Config — Used to retrieve jwtPrivateKey
  4. mongoose — create models and schema (We will use MongoDB online server)
  5. jsonwebtoken — generate and verify JWT
  6. bcrypt — hashing the password to store in the database

Step 1 :

First, We will create the folder for the project

mkdir nodejs-authenticationAuth
cd nodejs-authenticationAuth
npm init --yes

After creating the folder, we will initialize the project by using npm init. These are our folder structure for the project

-- config 
--- default.json
-- middleware
--- authentication.js
-- models
--- user.js
-- routes
--- user.js
-- index.js
-- package-lock.json
-- package.json

Step 2 :

In this section, we will create a model for the user. We will define the schema for the user that we are storing in our database. The schema consists of name, email, password, city, and isAdmin.
We have also added a function that will generate the JWT token for the login user. One more function we have added that will validate the schema. For this, we have added one npm module, Joi, which will use to validate the data we have provided.

In model, we can see that for email, we have added this validation  “email: Joi.string().min(10).max(60).required().email()“. It means an email should be in string format, having a minimum length of 10 and a maximum of 60. Email is a compulsory field. Like this, we have added for others also like password, city, name, and isAdmin.

const config = require('config');
// A json web token is essentially a long encoded text string. composed of three smaller parts
// 1 .header 2. Payload or body 3. signature
const jwt = require('jsonwebtoken');
// The most powerful schema description language and data validator for JavaScript.
const Joi = require('joi');
//mongoose to connect to the MongoDb 
const mongoose = require('mongoose');

// simple Schema
const UserSchemaInfo = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 4,
        maxlength: 60
    },
    email: {
        type: String,
        required: true,
        minlength: 6,
        maxlength:255,
        unique: true
    },
    password: {
        type: String,
        required: true,
        minlength: 6,
        maxlength:100
    },
    city: {
        type: String,
        minlength: 6,
        maxlength:100
    },
    isAdmin: {
        type: Boolean,
        required: true
    }
});

// generate the auth token by using the private key
UserSchemaInfo.methods.genAuthToken = function(){
    const token = jwt.sign({_id:this._id, isAdmin: this.isAdmin}, config.get('defaultKey'));
    return token;
};

const Userinfo = mongoose.model('User', UserSchemaInfo);


// function to validate the user that all required information is there or not.
function validateUserInfo(user){
    const userSchema = Joi.object({
        name: Joi.string().min(4).max(60).required(),
        email: Joi.string().min(4).max(60).required().email(),
        password: Joi.string().min(6).max(255).required(),
        city: Joi.string().min(6).max(100),
        isAdmin: Joi.boolean().required()
    });

    return userSchema.validate(user);
};

exports.UserInfo = Userinfo;
exports.validate = validateUserInfo;

Step 3:

In this step, we will add middleware. In the previous post, we have discussed the middleware. If you want to read more about middleware, you can visit this URL.

This section will create a function in which we will check that provided JWT is valid or invalid JWT. If the JWT is not right, we will throw the error.

const jwt = require('jsonwebtoken');
const config = require('config');

module.exports = function(req,res, next) {
    // check the token from the header 
    const token = req.headers["x-access-token"] || req.headers['authorization'];

    // if there is no auth token  response 

    if(!token) return res.status(401).send("Access denied. No token Provided");

    try {
        // if can verify the token set req.user and pass to next middleware
        const decoded = jwt.verify(token, config.get("defaultKey"));
        req.user = decoded;
        next();
    } catch (error) {
        res.status(400).send("invalid Token");
    }
}


Step 3:

In this section, we will discuss the different routes available for the user. Below are the routes for the user

  1. Create User
  2. Authenticate the user
  3. Check user type

In the first function, we are creating the user in which we will first validate the schema. After that, we will check that the user exists or not.

In the second function, we will authenticate the user with the provided credential. First, we will find the user with email after getting the result we will check the password using “bcrypt” module functionality.

In the third function, first, we will check that the proper token is provided or not after that, depending upon the user, we will respond to the user.

const express = require('express');
const router = express.Router();
const isLogin = require("../middleware/authentication");
const bycrypt = require("bcrypt");
const {UserInfo, validate} = require("../model/user");

// get detail of the by the towken
router.get('/currentUser', isLogin, async(req,res) => {
    const user = await UserInfo.findById(req.user._id).select("-password");
    let returnMessage = {
        user : user
    };
    if(user.isAdmin){
        returnMessage.message = 'User is Admin and it can perform Admin Activity';
    }else{
        returnMessage.message = 'User is basic User';
    }
    res.send(returnMessage);
});

// routes for the authenticating the user

router.post('/authenticateUser', async(req,res) => {
    const user = await UserInfo.findOne({ email: req.body.email});
    bycrypt.compare(req.body.password, user.password, function(err, result) {
        const token = user.genAuthToken();
        var message = {
            user: user
        };
        if(result){
            message.token = token;
            return res.status(200).send(message);
        }else{
            return res.status(200).send('Please check your credential');
        }
    });
});
 
// routes for creating the user
router.post('/', async (req, res) => {
    const error = validate(req.body);
    if(error.error) return res.status(400).send(error.error.details[0].message);

    // find if the user exist already
    let user = await UserInfo.findOne({email: req.body.email});
    if (user) return res.status(400).send("user already exist");

    user = new UserInfo({
        name:req.body.name,
        email:req.body.email,
        password:req.body.password,
        city:req.body.city,
        isAdmin:req.body.isAdmin
    });

    user.password = await bycrypt.hash(user.password, 20);

    await user.save();

    const token = user.genAuthToken();
    res.header("x-auth-token", token).send({
        _id:user._id,
        name: user.name,
        email:user.email
    });
})

module.exports = router;


Step 4:

In this section, try to understand the index.js file. It is our entrance file for the application. In this file, we have connected to our database for storing the user information. In this I have used my connection string to connect to the mongoDb database.

const express = require("express");
const config = require("config");
const mongoose = require("mongoose");
const userRouteInfo = require("./routes/user");
const port = process.env.PORT || 9001;

const app = express();

// config file to check the default key exist or not
if(!config.get("defaultKey")){
    process.exit(1);
};

//connection to the moongoose 
const connection_url = 'mongodb+srv://admin:Sp4Essssssssssssg65gmdAZPjU@cluster0.qutfh.mongodb.net/userData?retryWrites=true&w=majority'
mongoose.connect(connection_url, {
    useCreateIndex:true,
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => console.log('connected to MongoDb'))
.catch(err => console.error("could not connect to mongodb"));

app.use(express.json());

// adding the route
app.use("/api/users", userRouteInfo);

app.listen(port, () => 
    console.log(`listening on port ${port}`));

Step 5:

It is our final step in this we will first run our application by using

node index.js

After properly connection it will output like this in the command line

listening on port 9001
connected to MongoDb

Firstly we will try our user registration part

After the user’s successful creation, it will output the response with user_id and some necessary information.

User authentication screen

After successful authentication user will respond with the user information and the generated token. By using the token provided, we can access our next route that is getting login details

Conclusion

In this article, we have learned the basic approach to creating the authentication process by using JWT. In our JWT token, we have used user_id. We can provide any useful information. We have learned how to secure our routes and to authenticate the user.

]]>
How do Promises work in Javascript? https://spycoding.com/how-do-promises-work-in-javascript/?utm_source=rss&utm_medium=rss&utm_campaign=how-do-promises-work-in-javascript https://spycoding.com/how-do-promises-work-in-javascript/#comments Sun, 23 Aug 2020 13:54:39 +0000 https://spycoding.com/?p=72 Read more How do Promises work in Javascript?]]> Hello friends, we will try to learn the aspect of the promises in javascript how the promises work in the javascript. We will also learn how to use the promises effectively in the Javascript.

1. Definition of the promises in the Javascript

If we will try to understand promises in ordinary language. It will be like if I promise you to do one job for you, the next job will start when the first job completes. Take an example if we have messed our study room. Mother will come and say, please clean the room. If you clean the room, I will give you donuts. Mother has promised the children. If you compete with this task, I will provide you with the donuts. If you don’t, no donuts for you. Similarly, in the javascript, Promise means if you completed a task successfully will resolve; otherwise, it will reject the job.

In Javascript, promises is a way to handle asynchronous operation. We will Understand this article better if we know callbacks in the javascript. We can say that promises have two possible outcomes. It will complete (resolve), or it will fail to do the desire operation(reject). There are three states in the Promise

  • Pending : It is the initial state in that it has not been completed or rejected.
  • Resolve : Process is completed.
  • Reject : Process is not completed.

Let see small example of the Promise in the javascript:

const myPromise = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition is met) {    
        resolve('Promise completed');  
    } else {    
        reject('Promise rejected');  
    }
});

To create the Promise in JavaScript, we use the Promise constructor. The Promise we have created accepts a function as an argument. That function is called an executor. That executor has two features they are known as to resolve() and reject(). When we have called the Promise, the executor will automatically call based on the output if successful that resolve() otherwise reject().

If we want to see the Promise’s pending state, we can create a promise that will execute after specified seconds. Let’s take an example. If we want to see the Promise’s pending state, we can create a promise that will execute after specified seconds. Let’s take an example. In this, we have implemented a Promise after five seconds till the Five seconds will complete. The Promise will be in Pending state.

let promiseCompleted = true;

let learnPromise = new Promise(function (resolve, reject) {
    setTimeout(() => {
        if (promiseCompleted) {
            resolve("The promise will complete after 5 seconds.");
        } else {
            reject("It will be rejected if we will mark completed as reject.");
        }
    }, 5 * 1000);
});

The pending state will look the image given below. We can see that the state is pending state.

After five seconds, the Promise will complete according to the input parameter we have passed. In this case, the Promise will complete. It will look like this

Promise {<fulfilled>: "The promise will complete after 5 seconds."}
__proto__: Promise
[[PromiseStatus]]: "fulfilled"
[[PromiseValue]]: "The promise will complete after 5 seconds."

In case of rejection, it will look like this, PromiseStatus will reject in this case.

Promise {<rejected>: "It will be rejected if we will mark completed as reject."}
__proto__: Promise
[[PromiseStatus]]: "rejected"
[[PromiseValue]]: "It will be rejected if we will mark completed as reject."

Once the promise reaches it, it will fulfill or reject the state, but it cannot be switchback. Once a new Promise object is created, the promise is pending until it is resolved or rejected.

2. Promises chaining

We have a sequence of the task to be performed asynchronously. Means one after another task takes an example; we are saving a piece of user information first to upload his/her image. After that, we will want another job for this situation we can use Promise chaining. Let’s take an example; we will first fetch authenticate the user. After authentication, we want to check the user is admin or not.

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); // (*)

}).then(function(userInfo) {
  
  return userInfo;

}).then(function(isAuthenticated) { // (***)

  return isAuthenticated;

}).then(function(userType) {

  return userType;

});

3. Using A Promise Step by Step

  • In first phase we will call constructor to create Promise Object

const lazyLoad = new Promise();
  • It takes two parameters, one for success (resolve) and one for fail (reject):

Finally, there will be a condition. If the user condition is fulfilled, the Promise will resolve. Otherwise, it will reject.

let condition = true;

const lazyLoad = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});

Finally, we have created the first promise successfully step by step. Lets use it.

4.then( ) for resolved Promises

As we have discussed in the post, there are two conditions Promise will be resolved or get rejected. If the Promise is get resolved we will use then() keyword. We can use then keyword like this

lazyLoad.then((result) => {  
    console.log(result);
});

If our Promise got rejected(Fail), it will go into the catch method. If our condition get fail in that case, Promise will be rejected. Let’s see the example of the catch in the Promise.

lazyLoad.then((resolveMessage) => { 
    console.log(resolveMessage);
}).catch((rejectMessage) => { 
    console.log(rejectMessage);
});

So, if our condition got to fail, it will go to the Promise catch method.

5. finally() Method in the Promises

The finally() method returns a Promise. When the Promise is resolved or rejected based on the condition, we have provided while executing the Promises. finally() offer us a way to implement the code that is common for both resolve() or reject() method. So, finally() method can be used when we want to do some processing or clean the variable after the execution. In that case, we can use finally() method. Let’s take an example.

let condition = true;

const lazyLoad = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});

lazyLoad.then((resolveMessage) => { 
    console.log(resolveMessage);
}).catch((rejectMessage) => { 
    console.log(rejectMessage);
}).finally((message) => {
    condition = false;
});

6. Summary

  1. A Promise is an object in which return value in the future depends upon the user input. 
  2. A Promise always starts in the pending state.
  3. A Promise always will be resolve or in rejected mode.
  4. Use then() method while resolving the method.
  5. Use catch() method while rejecting the method.
  6. We can use multiple Promises for executing asynchronous calls(Promises chaining).
  7. Place the common in the finally() method to execute in both of the situations resolve or reject.

]]>
https://spycoding.com/how-do-promises-work-in-javascript/feed/ 2
How Does NodeJS middleware work? https://spycoding.com/how-does-nodejs-middleware-work/?utm_source=rss&utm_medium=rss&utm_campaign=how-does-nodejs-middleware-work Wed, 12 Aug 2020 12:03:43 +0000 https://spycoding.com/?p=59 Read more How Does NodeJS middleware work?]]> Friend’s here; we will try to understand how the Middleware works in the Nodejs. We will try to implement here own Middleware after that we will use Expressjs. Firstly we will try to understand what does Middleware means. After that, we will try to achieve our Middleware.

What is Middleware in the Nodejs?

Whenever we type any URL into our browser(client)
address bar. We are requesting information from the webserver where we want to do anything such as fetching any information. The server gets our request based on the requesting information. It interprets and prepares the response as per the request. It may have text, images any possible value.

When the webserver receives the request from the user in the form of data, the Nodejs gives you a request object. There will be the information on the browser, IP address, languages, and much more information in that object. Users can pass parameters also with that. After processing the request, NodeJs give back the response. These requests and responses are shortened to req and res.

Middleware functions are the best place to modify or update the req and res. For example, we are fetching the details of the user from the database. While fetching the data middleware will authenticate the user after authentication only webserver responds the exact data or the error that 401 (unauthorized access).
In a nutshell, we can say that. Middleware will give you access to the req and res. The next middleware function is a variable named next.

In short we can say that following for the Middleware:-

  1. As the names suggest, it comes in the middle of the request and response cycle.
  2. Middleware has access to re and res and req.
  3. Middleware has access to next for the request and response cycle.
Middleware in NodeJs

Middleware can do following tasks:

  1. Middleware execute the code
  2. Middleware make changes to request and response
  3. It can end the response cycle
  4. Middleware can execute the call that in the stack

These are the basic definitions of the Middleware in the NodejS. In the next section, we will learn what does next() do in the Middleware.

What is next() in the middleware?

Middleware is, in a nutshell, a function that will have access to the response cycle. In middleware, we can do many things, such as waiting for asynchronous databases or any network to proceed to the next step. We can take this example, and users are trying to edit the user information. In the middleware, we can check the authentication after properly authenticated we can check the authorization also. So in the middleware, we can do multiple things.

nodejs middleware next() example

In the above image, we can see the there we have taken an example in which we are updating the admin password. In that when the user will call the API to the web server, we will encrypt the data.
In the first phase, we will check that the login user is authenticated. If authentication fails, the web server will send a 401 error to the user.
After authentication, we will check the user is authorized to make the changes. If the user is authorized, the user will make changes, and the response cycle will complete. If the user is not authorized, the webserver will send a 401 error to the user.

Now we will see the types of middleware:

  1. Application-level middleware which generally uses app.use()
  2. Router level middleware which generally uses router.use()
  3. Built-in middleware like express
  4. The middleware which handled the error 
  5. There are some third ware middleware are there like cookieParser, bodyparser etc 

We will see examples for all the above middleware

  1. Application-level middleware

In the application level, we will take an example we have an eCommerce site there we have routes like:
checkOutProduct, getOrderDetails, isAdmin
Here all these API calls we do after the user is login into the system.
For that, we create a middleware in which before accessing the routes, it will check that the user is login or not.

const express = require('express');

// custom middleware create
const LoggerMiddleware = (req,res,next) =>{
    console.log(`Logged  ${req.url}  ${req.method} -- ${new Date()}`)
    next();
    // it will trigger next response if user is login it will return the data
    // otherwise return 401
}

const app = express()

// application level middleware
app.use(LoggerMiddleware);


// get user orders route
app.get('/getUserOrders',(req,res)=>{
    res.json({
        'status':true
    })
})

//checkout product POST METHOD
app.post('/checkOutProduct',(req,res)=>{
    res.json({
        'status':true
    })
})

// is admin
app.post('/isAdmin',(req,res)=>{
    res.json({
        'status':true
    })
})

app.listen(3002,(req,res)=>{
    console.log('server running on port 3002')
})

2. Router level middleware

In router level middleware, the same concept is there like application. In the application level, the middleware is at the application level in the route level middleware. It will protect a specific URL or route.
For example, there is one route in which the user wants to see all the transaction details.
But this is very confidential data, and only super admin has access to see the details. So there we need the router level. It will restrict unwanted access to the route.

const express = require('express');

const app = express();

const router = express.Router()

// route level middleware
router.use((req, res, next) => {
	next()
})

router.get("/user/paymentDetails/:userId", (req, res, next) => {
	next()
}, (req, res, next) => {
	next()
}, (req, res) => {
	res.json({
		status: true,
		id: req.params.id
	})
})

app.use('/', router)

app.listen(3000, (req, res) => {
	console.log('server running on 3000')
})

3. Third-party Middlewares

There are many third-party middlewares that we can install that module and use their functionality in our application. It will increase the speed of development. We can handle it at any level, like the application or the route level. For example bodyparser, cookieparser.

For installing the body parser run this command

 npm install body-parser
var express = require('express');
var  bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended:false})) // middleware 

app.use(bodyParser.json())

app.post('/userDetail',(req,res)=>{
  res.json({
    "status":true,
    "payload":req.body
  })
})
          
var server = app.listen(3000, function() {
      console.log('Listenint Port : 3000 ');
  });

4. Middleware which handled the error 

ExpressJS comes with default error handling params, which will act like middleware function in the same way as in application level and route level. For error handling, it comes with four parameters. For example

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something Went wrong please check!')
})

Conclusion

I have tried my best to discuss and describe the middleware concept. In a nutshell, we can say that when the user requests anything on browser or API request is generated with the user input. When the call reaches the webserver, it evaluates it that it’s coming from the right sources or not before sending back the final response. It will do all the needful operation. The operation will take place; that part is middleware. After evaluating all the possibilities, it will acknowledge the proper response to the user. I hope you have all liked the Article. Please give your valuable comment.

]]>
How to Create a Dynamic page in WordPress https://spycoding.com/how-to-create-a-dynamic-page-in-wordpress/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-create-a-dynamic-page-in-wordpress Fri, 07 Aug 2020 16:07:52 +0000 https://spycoding.com/?p=25 Read more How to Create a Dynamic page in WordPress]]> Hello, friends recently, while working on one of my projects, I need to fetch some details from the Database in WordPress. Earlier I have worked on many projects, but never fetch data from the database and display the result on the page as per the custom database table.

So, I thought to share this with all my friends may it will help someone. I will demonstrate step by step how we can achieve it. In this tutorial, we will learn How to add a dynamic page in WordPress. Let’s start it.

I will show you step by step but it will be better if you have prerequisite knowledge of PHP and mysql.

Let’s divide into three parts:-

  1. Database Part.
  2. PHP coding part.
  3. Creating a page in the WordPress Admin Panel and attach that template we have created in the second phase.

1. Database

First, we need to login to the phpMyAdmin from the Cpanel. You need to find the database name from the config file in the root directory of the website.

wordpress how to create dynamic page templete

We can see the wp-config.php file in the root directory. In the right, we can see the opened file
there you can find the database name in line number 23. Similarly, the user and password just below that.

After login creates a table in the selected database. After creating the table inserts some dummy data. I have added the sample data and table creation query.

CREATE TABLE `user_data` (
  `id` int(32) NOT NULL,
  `name` varchar(300) NOT NULL,
  `city` varchar(100) NOT NULL,
  `mobile` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_data` (`id`, `name`, `city`, `mobile`) VALUES
(1, 'John', 'NewYork', 132323232),
(2, 'Karl', 'Sydney', 324324232),
(3, 'David', 'Belgium', 132567232),
(4, 'Michel', 'Newyork', 23232323);

2. Create a Template for showing the data to the user

After creating the table and inserting the dummy data. Let’s create the page template for fetching the data from the database and showing it to the user. For that, we need to create a PHP file in the themes folder. We need to navigate to the theme folder in the wp-content folder in the root directory. In theme, folder navigates to the specific theme that you are using for your site.

Wordpress page creation

For example in the theme folder, there are four themes. I have used the Generate Press theme so, go that folder. I have created data.php in this file we will write our code to fetch the data from the database and display in our page.

After creating page we will need to write the code from that we will fetch the data and display on the front end.

Sample Code

<?php
/* Template Name: Display Dynamic Data */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

get_header();
    global $wpdb;
    $result = $wpdb->get_results("select * from user_data"); ?>
	<div id="primary" <?php generate_do_element_classes( 'content' ); ?>>
	    <!--Main Navigation-->

	<main id="main" <?php generate_do_element_classes( 'main' ); ?>>
		<div id="primary">
            <div class="card mt-4" id="bank_detail_after_fetch">
                <h5 class="card-header text-center">User Details</h5>
                  <div class="card-body">
                            <div class="table-responsive-md">
                              <table>
                                <tr>
                                  <td>Name</td>
                                  <td>City</td>
                                  <td>Mobile Number</td>
                                </tr>
                                <?php foreach ( $result as $data ) {    ?>
                                    <tr>
                                        <td><?php echo $data->name; ?></td>
                                        <td><?php echo $data->city; ?></td>
                                        <td><?php echo $data->mobile; ?></td>
                                    </tr>
                                <?php } ?>
                              </table>          
                            </div>
                  </div>
            </div>
    </div>
    </main> <!-- #main -->
</div><!-- #primary -->

	<?php
	/**
	 * generate_after_primary_content_area hook.
	 *
	 * @since 2.0
	 */
	do_action( 'generate_after_primary_content_area' );

	generate_construct_sidebars(); ?>
<?php 
get_footer();
 ?>

We will go through this whole code to understand the flow. At the top of the file we have defined the Template name in the Comment Section. From this, WordPress will fetch the template name.
After that we have called the get_header() function to call the header part.

In the second part we have defined the global variable to fetch the data from the database.
($result = $wpdb->get_results(“select * from user_data”))

After getting the data we have simply display the data the table format. In this way we fetch dynamic content from database. This is very simple and basic example. By using this concept
we can create many tool there we need to fetch the database from the table and display dynamic content like website where we can display city details, city pincode, bank details etc. We have just shown the data in the tabular form.

In the last we add the footer function to display the footer part. Second part is also completed in the third part we will see how we can use our template to create page and fetch dynamic data from the database in WordPress.

3. Creating a page in WordPress By Using the Page Template

In this section we will see how we can create dynamic page by using the Page template we have created in the last section. For this first we need to login into the WordPress dashboard using your credential.

After login, you will find the option to create page move to that section by clicking on the Add New Page Menu. In this, you will get an option to select a template in the page attribute section while creating New page. There add the title this will become the part of the URL. For example, you have added demo data. Then the URL for the page will be www.example.com/demo-data.

On this page, you will get the option to preview the page. By previewing the Page you will able to see the page you have created. On that page, you will see the data you have inserted in the table.
This is the small basic example to fetch the dynamic data from the self-created table in WordPress. By using method we can create a template by using the URL we can fetch different data based on the URL. We can take an example we have created a website in which by PIN Code we are fetching the area details. Consider this URL www.example.com/pincode/234235.

In this URL we have passed the PIN code in the URL. By that parameter we will fetch the data from the database and fill the content by using the fetched data. Similarly we can create many pages there we just need to change the URL and based on the URL we will fetch dynamic data from database in WordPress.

4. Conclusion

By using this we can create many tools based websites easily. If anyone needs help regarding then you can contact me at spycoding1@gmail.com. Although this is my first article I have tried my best to write. So we have learned a small topic on how to fetch the data from the database in WordPress using a custom database. The same thing happens in Plugins. In the future, I am going to create a series of Tutorials in that we will learn how we can create a Plugin. Please give your valuable comment to improve the content.

]]>