Home Blog Page 51

How to create react custom hooks to Fetch APIs using Axios

0
React Custom Hooks usefetch
React Custom Hooks usefetch

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll look at how to create react custom hooks to fetch APIs in Reactjs using Axios.

Custom hooks in react to fetch APIs help you to make your work easier and rapid instead of importing and using Axios again and again in each file to integrate frontend and backend.

Tons of API calls in your web application result in a slow down of the web app. Due to which it doesn’t ensure user performance. So, using optimized and fewer API calls can help you get better with the scalability of the application.

Introduction to custom hooks in react and Axios React

What is a custom hook

We create a custom hook for reducing code and reusability. A custom hook is a JavaScript function that starts with “use” and that can call other hooks in react functional component. There are already inbuilt react hooks such as useEffect, useState, useHistory, etc. Here we’ll be optimizing API calls in the frontend by creating our own hook.

Now, What is Axios actually

Axios in react is an HTTP client for browser and Node.js based on JavaScript Promises. Axios react makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used with any framework or regular pure JavaScript.

What we are going to build

We’ll be building our custom react hook function named “useAxios”. You can name it anything related such as “useApi” or “useFetch” to create custom hook in react. This will make the usual repetitive API fetch code reusable.

We’ll be using this https://jsonplaceholder.typicode.com/users to Fetch users. This is just a fake and free API for testing.

You’ll see this once you click on the URL. This is written in JSON format.

Let’s go with useAxios Approach!

That’s how you fetch API using Axios but this time we’re doing the same but in another custom file.

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

axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';

const useAxios = () => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await axios.get('/users');
      setResponse(res.data);
      setError(null);
    } catch (err) {
      setError(err);
    } finally {
      setLoading(false);
    }
  };

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

  return { response, error, loading };
};

export default useAxios;

If you’ll console.log the same stuff that we did above. You’ll see this result.

Then, App.js file will be written like this. For all the files that we’ll be fetching APIs in, we can use useAxios and make it reusable and worthy.

import useAxios from './useAxios';

const App = () => {
  const { response, error, loading } = useAxios();
  return (
    <div className="app">
      {loading ? (
        <div>Loading...</div>
      ) : (
        <div>
          {error && error.message}
          {response && response?.map((item) => <div>{item.title}</div>)}
        </div>
      )}
    </div>
  );
};

export default App;

Now we have super clean and easy-to-understand optimized code with fewer lines. That’s the power of making custom hooks. You can also go ahead and make this hook more customizable by adding parameters or functions that will let you work even more faster. For now, I’ve kept it simple and understandable.

That’s all!

Make sure you share it with your developer friends and connections.

learn more about react

Tools and Resources to learn react.js

How to use bootstrap in react

How to secure mongodb authorization for remotely access

0
mongodb create auth user credentail to access database
mongodb create auth user credentail to access database

Hi Guys, Welcome to Proto Coders Point. In this article will learn how to secure mongodb by creating auth user to remote access mongodb.

As you know, Mongodb is described in NoSQL database, it does not follow any relational DB structure, Instead, it stores data in JSON document.

When you install mongodb on ubuntu server, By default, mongodb remote connection security don’t have any authentication enabled, means anyone with you HOST IP can easily get access to your mongoDB services & perform CRUD operations without any mongodb authentication. which is not a secured way to integrate mongod database globally.

In this tutorial, We will cover how to secure mongodb authentication, so that only the user with mongodb auth credential can access DB.

Topic covered – Auth user creation in Mongodb

  1. Create MongoDB Super administrative user.
  2. Create user who can access db with read/write specific database.
  3. Create a user who has only read access in Mongodb.

Login into server using WINSCP & start putty terminal.

if you have problem, go through below video tutorial


1. Enabling mongodb security Authentication

To enable mongodb security, you need to edit mongod.conf file.

1. Open mongod.conf using nano editor

sudo nano /etc/mongod.conf

2. under security section add authorization : enabled

security:
authorization: enabled

Note: Here, security should not have space at start, & authorization should have 2 space at beginning below security.

refer screenshot for clear understanding

mongod.conf security auth enabling

After making mongodb auth enable save mongod.conf file & close it.

2. Restart mongod service & check status

After changing mongodb configuration, you need to restart mongod service, so that auth change get applied.

run below cmd

sudo systemctl restart mongod

then, check the status of mongod service,

sudo systemctl status mongod

If restart was successful, you will see active status as active(running)

Therefore, we have successfully enabled mongodb authorization globally. but we can’t access it right now as auth is been enabled, we need to create users to access database using credential.



MongoDb Auth user Creation

Follow below steps/cmd to create Auth user to access your mongodb database server, So that only the user with auth credential will be able to access DB.

use WinSCP to login into server & start putty terminal and then start mongo shell

mongosh

1. Create Admin User

Let’s create a super admin user, who will have access to read write any database in mongod

run below mongod queries to create users

use admin

mongodb create admin user

db.createUser(
            {
                user: "root",
                pwd: "root1234",
                roles: [ { role: "root", db: "admin" }, "readWriteAnyDatabase" ]
            }
        )

Therefore, super admin user is created with full read write any database access in mongod.

Restart mongod again to apply changed

sudo systemctl restart mongod

Now, goto mongoDB compass & connect using admin user credential

connection URI:

mongodb://root:root1234@< HOST IP >:27017
mongodb connection url string

2. Create user to access specific database

Now, let’s create a user who will have access to read/write only specific db assigned to him.

Only super user can assign and create new user to handle db, So first we need to use super admin credential to login, follow steps below

use admin

db.auth("root", "root1234")

now switch to database where you want to create user

 use rajatdb -> replace rajatdb with your dbname.

now create a user to access specific DB.

db.createUser(
            {
                user: "rootUser", 
                pwd: "rootUser1234",
                roles: [ { role: "readWrite", db: "rajatdb" } ]
            }
        )

Above user can only access rajatdb, the role assigned to this user is readWrite.

now, run restart mongod cmd.

Now, go back to mongoDB compass & connect using user credential we created.

connection URI: mongodb://rootUser:rootUser1234@< HOST IP >:27017/rajatdb?authSource=rajatdb

mongodb connection url string
mongodb connection url string

3. Create a user who has only read access to specific database.

Now, let’s create a user which can only read/view the data but can’t make changes.

repeat the same step

auth as super

use admin

db.auth("root", "root1234")

now switch to database where you want to create user

use rajatdb

 db.createUser(
            {
                user: "ReadUser",
                pwd: "read1234",
                roles: [ { role: "read", db: "rajatdb" } ]
            }
        )

Here the role assigned to this user is read, so he can only view & read data from database.

now, run restart mongod cmd.

Now, go back to mongoDB compass & connect using user credential we created.

connection URI: mongodb://ReadUser:read1234@< HOST IP >:27017/rajatdb?authSource=rajatdb


Why mongodb is better than sql – MongoDB vs SQL

0
mongodb vs mysql
mongodb vs mysql

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll know why to use MongoDB when we already have a language like SQL which is being used for so many years. Why MongoDB is faster than SQL and when to choose MongoDB over SQL.

SQL databases have always been used the most in the world of technologies and have been the primary source of data storage for so many years. Data in SQL databases are stored in a relational way so it is called relational databases. In this modern world, we prefer to use non-relational databases which make the work so much easier and non-hectic.

What is the difference between MongoDB and MySQL?

As you might be knowing that, MongoDB is completely an open-source database which is been developed by MongoDB, Inc. MongoDB stores data in JSON format documents that vary in structure. It is a popular NoSQL database whereas,

And as I said in the above sentence, MySQL is one of the popular relational database management systems (i.e. RDBMS) that is developed, distributed, and supported by Oracle Corporation.

The difference between MongoDB & MySQL Databases is the way they handle data.

MySQL vs MongoDB

In MySQL, you’re only allowed to store types like int, text, and a few others in fields. (flat data)

In MongoDB, you can store rich data structures with sub-fields being objects as well.

the structure has to be pre-defined in MySQL. MUST pre-define the tables and structures.

With MongoDB, you can literally throw whatever you want into the collection and it’ll store it.

To create a connection between the MongoDB database and the express.js server, we use a JavaScript Object-oriented library called Mongoose. It lets you structure and writes queries, way simpler!

difference between mongodb and mysql

Why mongodb is better than SQL as your data storage

Let’s take a scenario to understand How fast MongoDB works instead of SQL.

Imagine you’re a freelancer and you have got a project!

You are asked to make a brand new social media platform.

Your client says:

“The site needs to be fast! We’re going global”,

“We also need comments and reply feature”,

“Don’t forget about likes”,

“Oh, rating for the user profile”,

“We need the section of a recent post”,

“And make sure we have a really easy way to tag people”,

You’re thinking of all these features!

In SQL, it’s going to take lots of tables and columns to structure the data, and also it needs to be fast. How can we make data response faster? What if we can do all these things in a simpler way and make it fast?

Instead of designing it with tables, we can use documents. MongoDB helps us to do this with its document model. with MongoDB you can take care of almost all the features.

Simply, you can do something like this:

So in MongoDB data is been stored in JSON form, i.e. in key-value pair.

{
"_id": "e194jsd784yfd64hd8ahf"
"name": "Shruti Panjwani",
"bio": "I am freelance full stack developer",
"posts": [
{"post": "This is my first post"},
{"post": "This is my second post"},
],
"company": "Coders Troop",
"likes": [38, 18],
}

That is why use mongodb over sql. Did you learn something new and interesting today? If yes, Share it with your friends 🙂 Thank you.

How to access mongodb globally – mongodb remote connection

0
mongodb remote connection
mongodb remote connection

Hi Guys, Welcome to Proto Coders Point. In this article will learn How to config mongodb to access globally that is mongodb remote connection, so that we can preform CRUD operation into mongo database by using Mongodb compass GUI tool by using server ip.

Basically, mongodb allow access from anywhere by using IP address & port in DB compass.

MongoDB remote connection – Globally access

1. Add global bindIp in mongod.config

To make database globally accessable, you need to change in mongod.conf file bindIP to 0.0.0.0 or your server IP.

1. Open mongod.conf file

sudo vim /etc/mongod.conf

press shift + i (key) to go into INSERT mode and change bindIp to 0.0.0.0.

net:
    port: 27017
    bindIp: 0.0.0.0 

press ESC (key) to come out from INSERT mode, then press :wq to save & exit mongod.conf.

In mongod.conf file change 127.0.0.1 to 0.0.0.0

2. AWS server side – give access permission TCP mongoDB port

In AWS dashboard navigate to

EC2 > Instance > click on instance ID > Security > Security groups > Edit inBound rules > Add rule

Here select type > select custom TCP & port range enter 27017( i.e. mongodb port ).

then same the rules


3. Connect to Database using MongoDB compass

Open db compass, connect > new Connection > Paste your connection string

mongodb connection url
mongodb compass connection url string

mongodb://<HOST IP>:27017/

Example:

mongodb://18.191.199.130:27017/


Therefore, you have successfully, changed your database to be accessed globally using host IP.

How to use bootstrap in React – reactstrap

0

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll learn about how to use Bootstrap in React.

Basically, Bootstrap is an open-source and free CSS framework focused on responsive, mobile-first front-end web development. It contains CSS and JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components.

There are multiple ways of using bootstrap in react:-

  1. Downloading Bootstrap and Manually importing as a dependence, Using Bootstrap CDN
  2. Using React Bootstrap npm package

Downloading Bootstrap and Manually importing as a dependency

You can add BootstrapCDN using as a link to your index.html file in the public folder of your React application.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" 
    integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" 
    crossorigin="anonymous">
    
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.
      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.
      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
    
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
    crossorigin="anonymous"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" 
    integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" 
    crossorigin="anonymous"></script>
    
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" 
    integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" 
    crossorigin="anonymous"></script>
    
  </body>
</html>

Using react-bootstrap npm package

I prefer adding that using the react-bootstrap or reactstrap npm package so we’ll be looking at how to do so?

npm install react-bootstrap bootstrap@5.1.3

Now you have the bootstrap installed with this command.

The next step to use Bootstrap is to actually import elements and use them.

You can use Bootstrap directly on elements and components in your React app by applying the in-built classes just like we use in any other programming language. For eg:- Let’s take up a Button Element from Bootstrap.

import Button from 'react-bootstrap/Button';

// or 
import { Button } from 'react-bootstrap';

BootStrap React Examples

React bootstrap Button Component

Then let’s use this Button Component in jsx, just as we do in HTML file

<Button variant="primary">Primary</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="success">Success</Button>
<Button variant="warning">Warning</Button>
<Button variant="danger">Danger</Button>
<Button variant="light">Light</Button>
<Button variant="info">Info</Button>
<Button variant="link">Link</Button>
<Button variant="dark">Dark</Button>

React bootstrap Card Component

Let’s see an example of Cards now. The card is a container, Card.Img is an Image element, Card.body takes in content in the card and inside the body, we have Title & More Text. You can give this variant too.

<Card style={{ width: '18rem' }}>
  <Card.Img variant="top" src="holder.js/100px180" />
  <Card.Body>
    <Card.Title>Card Title</Card.Title>
    <Card.Text>
      Some quick example text to build on the card title and make up the bulk of
      the card's content.
    </Card.Text>
    <Button variant="primary">Go somewhere</Button>
  </Card.Body>
</Card>

React bootstrap Alert Component

Let’s have a look at Alerts now that provides contextual feedback messages for typical user actions with the handful of available and flexible alert messages. These are the variants.

[
  'primary',
  'secondary',
  'success',
  'danger',
  'warning',
  'info',
  'light',
  'dark',
].map((variant, idx) => (
  <Alert key={idx} variant={variant}>
    This is a {variant} alert—check it out!
  </Alert>
));

We can use more such components to make our work effective and rapid such as Pagination, Progress Bars, Popovers, Spinners, Breadcrumbs, Dropdowns, Inputs, Lists, Modals, etc. There are many!

In this article, we’ve explored a few different ways in which we can integrate Bootstrap with our React applications. We have also seen how we can use two of the most popular React Bootstrap libraries, namely react-bootstrap and reactstrap

Don’t forget to share it with your connections 🙂

Install MongoDB on AWS ubuntu server

0
Install MongoDb on Ubuntu AWS Server
Install MongoDb on Ubuntu AWS Server

Hi Guys, Welcome to Proto Coders Point. In this AWS tutorial, we will Install MongoDB on Amazon ubuntu server instance.

In you don’t know how to create AWS ubuntu server & get connected to aws server using WinSCP, then checkout below article, where I have explained in step by step instruction create ubuntu server on AWS.


Lets get started

Install MongoDB community server edition on ubuntu AWS server

Below are some commands that you need to run on your ubuntu aws server to install mongoDB on cloud server.

1. Connect to AWS server & load putty terminal

I assume, you know how to connect to AWS cloud server using WinSCP & open the putty terminal to install mongoDB on server side.

winscp start putty terminal
winscp start putty terminal
putty terminal
putty terminal

Here is where you need to run cmds to install mongoDB.


2. Import MongoDB public GPG keys

To Install mongoDB we need to first download/import GPG key, in WinSCP putty terminal run below command

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

The cmd will respond OK.

If you get error, saying gnupg not install, then install it and retry above cmd.

1. Install gnupg

sudo apt-get install gnupg

2. retry importing GPG key

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

3. Create list file for MongoDB

Create a file which will hae mongodb org list version for your ubuntu.

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

4. local package reload

Run below cmd to reload all the local package database.

sudo apt-get update

5. Install MongoDb on ubuntu server aws

Now, finally we can install MongoDB on Ubuntu server, run below command.

Install MongoDb latest version

sudo apt-get install -y mongodb-org

Install specific version on mongo database

sudo apt-get install -y mongodb-org=5.0.5 mongodb-org-database=5.0.5 mongodb-org-server=5.0.5 mongodb-org-shell=5.0.5 mongodb-org-mongos=5.0.5 mongodb-org-tools=5.0.5

After successfuly installation, run below 6 echo cmds.

echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-database hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-org-shell hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections

We need to hold/pin, mongoDb from getting unintended upgrade version of mongodb-org, so below 6 cmd will hold, apt-get upgrade to update mongo database version.


6. How to start mongod service

To start/run, stop, or restart mongod server check below cmds

  1. sudo systemctl start mongod
  2. sudo systemctl stop mongod
  3. sudo systemctl restart mongod

Run mongoDb query

Start mongoD, just enter mongosh, which will take you to mongodb shell, where you can execute mongod queries to perform CRUD operations like creating/insertinf data, reading, updating & deleting the data from database.

mongosh

Therefore, we have successfully installed mongodb on ubuntu aws server.



Uninstall mongoDB from ubuntu completely

You can easily remove/uninstall mongod from ubuntu completely.

follow below steps to remove mongodb.

1. Stop mongod

sudo systemctl stop mongod

2. remove mongodb-org package

sudo apt-get purge mongodb-org*

3. remove/delete data directory

The below cmd will remove database & log files

sudo rm -r /var/log/mongodb

sudo rm -r /var/lib/mongodb


Conclusion

Therefore, above are the steps and command to install mongodb and uninstall it in ubuntu operating system.