Search

What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. So let’s get started.What is Axios? (A little bit of history) Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. Why Do We Need Axios in React? Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: Don't worry if you are not familiar with the code, we will learn that later. Using FETCH API:   const getPostsData = () => {   fetch(‘https://jsonplaceholder.typicode.com/posts’)   .then(response => response.json())   .then(data => console.log(data))   .catch(error => console.log(error));   } }  getPostsData();Using AXIOS: const getPostsData = () => {   axios   .get("https://jsonplaceholder.typicode.com/posts")   .then(data => console.log(data.data))   .catch(error => console.log(error));   };  getPostsData();You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  Prerequisites In order to use Axios with React, you’ll need the following: Install Node (v 10.7 or above). And if it is already installed, check the version by using npm -v  A React project setup with Create React App or any React boilerplate If you want to learn more about Axios library, head up to this link.  Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. Installing Axios In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment. Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. Using npm: $ npm install axios  Using bower package manager: $ bower install axios  Using yarn:  $ yarn add axios  Using unpkg CDN:   <script src="https://unpkg.com/axios/dist/axios.min.js"></script>  Using jsDelivr CDN:    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>  It’s not as complicated as you  might think it’d be.  Fetching and Consuming Data with a Axios (GET-POST-DELETE) Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. Performing GET Request with Axios Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. Here we are using JSON placeholder API for fetching the dummy list data of users. import React from 'react';  import axios from 'axios';  export default class MyList extends React.Component {   state = {   persons: []   }  componentDidMount() {   axios.get(`https://jsonplaceholder.typicode.com/users`)   .then(response => { const users = response.data;   this.setState ({users});   })   }  render() {   return (   < ul >   {this.state.users.map (user => {user.name} )}   < /ul >   )   }  }In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  We can also retrieve other Information like status code and others received with the response. Performing POST Request with Axios Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component {  state = {  userName: '',  }  handleChange = event => {  this.setState({ userName: event.target.value });  }  handleSubmit = event => {  event.preventDefault();  const user = {  userName: this.state.userName  };  axios.post(`https://jsonplaceholder.typicode.com/users`, { user })  .then(res => {  console.log(res);  console.log(res.data);  })[Text Wrapping Break] }  render() {  return (  <div>  <form onSubmit={this.handleSubmit}>  <label>  User Name:  <input type="text" name="name" onChange={this.handleChange}/>  </label>  <button type="submit">Add</button>  </form>  </div>  )  }  }In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. Performing POST Request with Axios Finally, the delete method. axios.delete is used to make a Delete request to the server. axiox.delete accepts two parameters: url and optional config.  axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); We can use config.data to set the request body and headers as shown in the below snippet. Consider the same component as above and modify the request as follows: handleSubmit = event => {   event.preventDefault();   axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)   .then(res => {   console.log(res);   console.log(res.data);   })  } And you are done! — you’ve got a transformed and simplified React appSending custom headers with Axios Sending custom headers with Axios is very simple and straightforward.  It is done by passing an object containing the headers as the last argument.  See the below code reference:  const options = {   headers: {'X-Custom-Header': 'value'}  };  axios.post('/save', { a: 50 }, options);Looking at the response object When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. status: It is basically the HTTP code returned from the server. statusText: it refers to the HTTP status message returned by the server. headers: It contains all the headers sent back by the server. config: It has the original request configuration. request: It is the actual XMLHttpRequest object (when it is running in a browser)Looking at the error object And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: message: the error message text. response: the response object (if received) as described in the previous section. request: the actual XMLHttpRequest object (when running in a browser). config: the original request configuration. Features of Axios Library as per the Documentation: Automatically transforms for JSON data Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() Transform request and response data Make HTTP requests from Node.js Make XMLHttpRequests from the browser Client-side support for protecting against XSRF Supports the Promise API Intercept request and response: HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. Has an ability to cancel requests It has a built-in feature that provides client-side protection against cross-site request forgery. In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. MAKING MULTIPLE REQUESTS WITH AXIOS With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. axios.all([   axios.get('https://api.github.com/users/defunkt),   axios.get('https://api.github.com/users/evanphx)  ])  .then(response => {   console.log('Date created: ', response[0].data.created_at);   console.log('Date created: ', response[1].data.created_at);  }); What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.  Think About Abstraction  In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });And then simply abstract the URL like shown:  async getPostsData() { const response = await api.get();   try {   this.setState({   posts: response.data.posts,   isLoading: false   });   } catch (error) {   this.setState({ error, isLoading: false });   }  }Shorthand Methods in Axios  You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. Do you know that Axios has some shorthand methods for performing different HTTP requests?  Check them below:  axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Some Awesome Facts about Axios  Wondering about some cool facts about Axios? Let’s check them out! For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. axios({   method: "get",   url: "/myFilePath",   responseType: "blob",   onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round(   (progressEvent.loaded * 100) / progressEvent.total   );  console.log(percentCompleted)   this.setState({   loadingPercent: percentCompleted,   });   },  }).then((response) => {   alert("We are Ready!");  });ConclusionI hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch api.  So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. Happy Learning.

What is the Use of Axios in React?

6K
What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  

We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. 

There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. 

So let’s get started.

What is Axios? (A little bit of history) 

  • Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  
  • It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. 
  • Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. 

Why Do We Need Axios in React? 

Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  

Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. 

When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? 

  • So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? 
  • Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. 
  • And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. 
  • Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: 
  • Don't worry if you are not familiar with the code, we will learn that later. 

Using FETCH API:   

const getPostsData = () => {
  fetch(‘https://jsonplaceholder.typicode.com/posts’)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
  }
}
 getPostsData();

Using AXIOS: 

const getPostsData = () => {
  axios
  .get("https://jsonplaceholder.typicode.com/posts")
  .then(data => console.log(data.data))
  .catch(error => console.log(error));
  };
 getPostsData();

You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  

Prerequisites 

In order to use Axios with React, you’ll need the following: 

  1. Install Node (v 10.7 or above). 

And if it is already installed, check the version by using 

npm -v  
  1. A React project setup with Create React App or any React boilerplate 

If you want to learn more about Axios library, head up to this link.  

Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. 

Installing Axios 

In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. 

There are many ways to install Axios. You can pick any of them based on your system environment. 

Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. 

Using npm: 

$ npm install axios  

Using bower package manager: 

$ bower install axios  

Using yarn:  

$ yarn add axios  

Using unpkg CDN:   

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>  

Using jsDelivr CDN:    

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>  

It’s not as complicated as you  might think it’d be.  

Fetching and Consuming Data with a Axios (GET-POST-DELETE) 

Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. 

In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. 

Performing GET Request with Axios 

Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. 

Here we are using JSON placeholder API for fetching the dummy list data of users. 

import React from 'react';
 import axios from 'axios';
 export default class MyList extends React.Component {
  state = {
  persons: []
  }
 componentDidMount() {
  axios.get(`https://jsonplaceholder.typicode.com/users`)
  .then(response => {
const users = response.data;
  this.setState ({users});
  })
  }
 render() {
  return (
  < ul >
  {this.state.users.map (user =>  {user.name}   )}
  < /ul >
  )
  }
 }

In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  

We can also retrieve other Information like status code and others received with the response. 

Performing POST Request with Axios 

Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) 

import React from 'react';
import axios from 'axios';
export default class AddUser extends React.Component {
 state = {
 userName: '',
 }
 handleChange = event => {
 this.setState({ userName: event.target.value });
 }
 handleSubmit = event => {
 event.preventDefault();
 const user = {
 userName: this.state.userName
 };
 axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
 .then(res => {
 console.log(res);
 console.log(res.data);
 })[Text Wrapping Break] }
 render() {
 return (
 <div>
 <form onSubmit={this.handleSubmit}>
 <label>
 User Name:
 <input type="text" name="name" onChange={this.handleChange}/>
 </label>
 <button type="submit">Add</button>
 </form>
 </div>
 )
 }
 }

In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. 

Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. 

Performing POST Request with Axios 

Finally, the delete method. axios.delete is used to make a Delete request to the server. 

axiox.delete accepts two parameters: url and optional config.  

axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); 

We can use config.data to set the request body and headers as shown in the below snippet. 

Consider the same component as above and modify the request as follows: 

handleSubmit = event => {
  event.preventDefault();
  axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)
  .then(res => {
  console.log(res);
  console.log(res.data);
  })
 } 

And you are done! — you’ve got a transformed and simplified React app

Sending custom headers with Axios 

Sending custom headers with Axios is very simple and straightforward.  

It is done by passing an object containing the headers as the last argument.  

See the below code reference:  

const options = {
  headers: {'X-Custom-Header': 'value'}
 };
 axios.post('/save', { a: 50 }, options);

Looking at the response object 

When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: 

  • data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. 
  • statusIt is basically the HTTP code returned from the server. 
  • statusText: it refers to the HTTP status message returned by the server. 
  • headers: It contains all the headers sent back by the server. 
  • config: It has the original request configuration. 
  • request: It is the actual XMLHttpRequest object (when it is running in a browser)

Looking at the error object 

And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: 

  • message: the error message text. 
  • response: the response object (if received) as described in the previous section. 
  • request: the actual XMLHttpRequest object (when running in a browser). 
  • configthe original request configuration. 

Features of Axios Library as per the Documentation: 

  • Automatically transforms for JSON data 

Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() 

  • Transform request and response data 
  • Make HTTP requests from Node.js 
  • Make XMLHttpRequests from the browser 
  • Client-side support for protecting against XSRF 
  • Supports the Promise API 
  • Intercept request and response: 

HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. 

  • Has an ability to cancel requests 

It has a built-in feature that provides client-side protection against cross-site request forgery. 

In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. 

MAKING MULTIPLE REQUESTS WITH AXIOS 

With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. 

Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. 

axios.all([
  axios.get('https://api.github.com/users/defunkt),
  axios.get('https://api.github.com/users/evanphx)
 ])
 .then(response => {
  console.log('Date created: ', response[0].data.created_at);
  console.log('Date created: ', response[1].data.created_at);
 }); 

What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallelreturn the response data and will console the created_at object from each of the API responses.  

Think About Abstraction  

In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   

const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });

And then simply abstract the URL like shown:  

async getPostsData() {
const response = await api.get();
  try {
  this.setState({
  posts: response.data.posts,
  isLoading: false
  });
  } catch (error) {
  this.setState({ error, isLoading: false });
  }
 }

Shorthand Methods in Axios  

You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. 

Do you know that Axios has some shorthand methods for performing different HTTP requests?  

Check them below:  

  • axios.request(config) 
  • axios.get(url[, config]) 
  • axios.delete(url[, config]) 
  • axios.head(url[, config]) 
  • axios.options(url[, config]) 
  • axios.post(url[, data[, config]]) 
  • axios.put(url[, data[, config]]) 
  • axios.patch(url[, data[, config]]) 

Some Awesome Facts about Axios  

Wondering about some cool facts about Axios? Let’s check them out! 

  • For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. 
  • Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  
  • In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. 
axios({
  method: "get",
  url: "/myFilePath",
  responseType: "blob",
  onDownloadProgress: (progressEvent) => {
const percentCompleted = Math.round(
  (progressEvent.loaded * 100) / progressEvent.total
  );
 console.log(percentCompleted)
  this.setState({
  loadingPercent: percentCompleted,
  });
  },
 }).then((response) => {
  alert("We are Ready!");
 });

Conclusion

I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  

In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. 

We also got an idea about why it is a better approach than a normal fetch api.  

So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. 

Happy Learning.

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Step-by-Step: Create a React Project From Scratch

Hello learners. In this tutorial we will learn How to create a new React app. Before we begin, we need to understand few things. These tutorials are aimed for the aspiring and seasoned web developers & designer. If you are an aspiring web developer who wants to establish their career in React and other modern frontend technologies, these tutorials will provide you the basic understanding that you need to learn, rehearse and practice. And some additional links as a part of suggestive reading, which you can further dwell upon. As a lifelong learner, we need to be open to new ideas however they may challenge your beliefs at first.  Technology is a work in progress. It composes of sections of stable parts which can be applied to solve the problem of our lives. And some sections which are the part of debate and undergoing experimentation and transformation by the pioneers who forged & nurture the systems. The cutting-edge technology tends to follow approximately the following adoption curve.Source: Crossing the Chasm  (1990) -Author: Geoffrey Moore   Technology Adoption Lifecycle As you can see, the curve is divided among 5 sections as categorized by the work of: Innovators Early adopters Early majority Late majority  LaggardsArea under the curve represents number of customers  During the second phase, there is an important phase known as Chasm. Any nascent technology which becomes main stream must grow this phase with the help of Early adopters along with innovators. And every promising technology has gone through this phase before it has gained enough momentum and has gone mainstream. Before we learn React. We need to learn some concepts. And It will be good to have some basic understanding of how internet works. There are various technical jargon associated and it is a broad topic. If you are complete starter, I hope it will give you some base. We will try to understand and answer the following: What is Client & Server? What is meant by HTTP?Client & Server When a user is connected to the internet with the help of browser (Google Chrome, Mozilla Firefox, Internet Explorer, Safari & Opera). And when we type or do the google search with the help of keywords. We are presented a list of search results. The user computer is a client and google search engine act as server. As it serves to your queries in the form of the best matched results in a reasonable short time, it is good to say that the search results are produced at the blink of an eye. HTTPWorld wide web (W3C) is a consortium which governs the internet. It has set of rules and protocols which defines how the different machines can communicate over the internet. Sir Tim burner Lee is the inventor of the W3C.HTTP is a protocol, which tells and describe the transmission of hypermedia on the internet. It is designed based on the client server concept. In which one system is a client which seeks the information and other system is a server who act and fulfil the request of the client. In HTTP, there are various status codes for server, and it describes the status of server based on the client request.  Whether the request has been Successful any error conditions on Client & Server redirected by server & so on.1.a(1) HTML HTML is a mark-up language which is used to create hypermedia document on the internet. Hypermedia based documents are used to exchange information on the internet. HTML should not be confused with programming language such as C, C++, Java & C#. Let’s write a Hello World! HTML document as below:        HTML 5 Document    Hello World!  To run the above code we can write it down or copy & paste in our favorite text editor and save it as Hello World.html. Please note .html is the file extension. And once we open the file with the browser it will show us the output as below.HTML is composed of various tags which defines the document and it's semantic. Semantic add meaning to the content as expressed by enclosing tags and it is not purely for visual presentation purpose.  The HTML 5 document begins with  HTML has also undergone various revisions and modifications. For e.g. If We need to present the information as paragraph.  Then we need to use < p > tag. For Tabular data < table >, Order list & unordered list < ul > and so on. References:Complete list of HTML references.HTML Standard & Draft list. 1.a(2)CSS Brief history CSS refers to the cascading style sheets. In the beginning year of the HTML, when HTML was used primarily to exchange information with the help of HTML document on the internet.   There was limited functionality to style the webpages. In fact, there were some tags which allows to style a page and change its formatting. But there was no separation of concerns, for e.g. the formatting tag and its associated attributes were often mixed with semantic HTML.And one of the early innovators Håkon Wium Lie recognized that there is a need of web page styling language which can address the presentation part of the webpages including the layout. And there is a need of separation of concerns.  Håkon Wium Lie along with the co-inventor Bert Bos had written the specification of CSS. < table> & its sibling tags were heavily used to structure the layout of the webpages. For E.g. To create multi column layout < table> were frequently used. It worked well to create the initial push to the web layouts, but it has own draw backs.  More on the history of CSSTo know more about how we can use CSS, we will start with previous code. To change the text color of Hello World! from black to green, we will declare a stylesheet called text.css. Naming convention for filename plays important rule, in recalling the file name when your source code becomes huge. It is good to start building on these habits. Hello World.html           HTML 5 Document    Hello World!    Text.css body{  font-family: 'Arial', Helvetica, Verdana;  color: red;  font-weight: bold;  font-size: large;  }As you can see from the browser, it displays the Hello World! text in red color and font appearance is bold & larger. CSS has lots of modules which helps us to create sophisticated layouts, cool animations, image processing using css filters, accessibility (a11y) & much more. The current version of CSS is CSS3. As technology gradually evolved, so did the CSS.  It is maintained by CSS working group, which consists of invited experts and working group members.  If you are interested to explore more you may check some of these links. Reference: CSS AlmanacCool tricks  Homer CSS (2008) http://www.romancortes.com/blog/homer-css/ Animated your HTML http://animateyourhtml5.appspot.com/ 1.a(3) JavaScript JavaScript is used to bring interactivity on the web pages. JavaScript is based on the ECMA Script standard.  Every browser has JavaScript engines, which interpret the JavaScript code. As described in the previous sections that the HTML is responsible for the structure and semantic aspect for the webpage. And with the help of CSS, the look and feel, advanced layouts and interactivity can be added using animation and pseudo classes. JavaScript brings lots of interactivity to your pages. It is good to say that it adds wings to your creation. But sometimes these wings catch the fire, so we also know how to troubleshoot and prevent such instances from happening.  For e.g. If you ask your user to input their age. To validate the age, we can write the JavaScript code and validate, whether the input is correct or not. To recap and understand the HTML, CSS and JavaScript in brief. We can refer to the above presentation. 2. ECMA Script and new versions ECMAScript describes the functionality of JavaScript. ECMAScript is maintained by ECMA International. The aim of ECMA Script is to ensure that webpages can run the same JavaScript code across different browser, & it is also interoperable with other programming language. In this context the Interoperability means that other programming language can invoke JavaScript function. Programming languages such as Dart can run JavaScript code. Some framework such as Blazor in the world of . NET can invoke functions written in JavaScript. In terms of specification it tries to draws the line of standard for different browser vendors. Microsoft, Firefox, Google, Chrome, Opera & Apple each has its own browsers which runs on different operating systems whether it is on Windows, Linux and macOS. Sometimes the browser vendor takes a lead while implementing a feature. But the specifications for that feature are written later by standard body (ECMA International). The new feature may be adopted by another browsers vendor later in the evolution process.  Different browser vendor has different development life cycle in terms of feature’s implementation. And it takes time for the specification to become a standard. And the new version of browser is released by multiple vendor with the specification and takes time to become a standard on Web. In past few years since ECMAScript has undergone various revisions and changes as described by ES6, ES7, ES8 & ES9 & more we will see in future. And these changes have resulted into the major impact on the JavaScript syntax. More references: ECMA Script version history https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_ResourcesECMA Script https://www.ecma-international.org/publications/standards/Ecma-262.htm 2. Intro to React & Virtual DOM React is a library which is publicly released by Facebook in 2013. React was created by Jordan Walke, a software engineer working at Facebook. React allows us to divide our code into components. And these components communicate with each other in a unidirectional flow. As the components follows a standard development structure in nomenclature and design patterns. This helps in reducing of the knowledge gaps when different team members work and manage a project in which they have not worked from scratch.  React is based on the Functional programming principles as the design pattern. It is also follow the DRY principle. DRY stands for Don’t repeat yourself. That means any piece of code which serves a specific task or function should not be repeated as the duplicate code. But we can declare it as a component and increase the reusability. Design pattern is a wide topic. If you are interested to know more about the design pattern you may check out these references. https://addyosmani.com/resources/essentialjsdesignpatterns/book/https://refactoring.guru/design-patterns2.b Quick timeline of React release Technology goes through a lot of wear and tear before it is adopted in mainstream and it also need to prove it's worth in real life production environment. The complete timeline of React release is available on GitHub. Some of the interesting highlights from React release. VersionRelease DateDescription0.3.029th May 2013Public release0.13.010th March 2015Support for ES6 Classes15.007th April 2016New changes on how React interacts with DOM, added support for SVG attributes, Dropped support for IE816.026th September 2017MIT license. Reduced file size. Better error handling16.505th September 2018Added support for React Devtools profiler (Flame chart, Ranked chart, Component chart & more)16.816th February 2019Introduced concept of hooksReference: https://github.com/facebook/react/blob/master/CHANGELOG.md#https://blog.risingstack.com/the-history-of-react-js-on-a-timeline/2.c Component driven development  The beauty to work with React is that you can structure and assemble your code in components. The parent component can contain various child components. The parent component passes the data values to child, to maintain the uni-directional data flow. For data driven apps, React seems to be a good choice. 2.d  Virtual DOM - The secret sauce of DOM Optimisation Before we understand Virtual DOM, let’s take a look at DOM. DOM refers to document object model.DOM is referred by the browser to render the HTML. The HTML is converted into DOM. To simply visualise the DOM you can think of a tree trunk and which has its roots spread down below.In DOM visualisation tree we can see that there are different nodes which are connected to html. In DOM, whenever the new nodes are inserted and deleted there is cost in terms of computation and memory footprint during such operations. And this is a little costly affair. Virtual DOM acts as performance optimiser in these operations.  The Virtual DOM has two copies, one is the master copy of the node and another one is the copy of the changes to be done. Virtual DOM reduces the cost in terms of memory and processing time to apply the changes. It applies the minimal changes required on the DOM. The process is also called reconciliation and is achieved by render() function in React. Reference: View Live DOM Tree: https://software.hixie.ch/utilities/js/live-dom-viewer/d3.DOM Visualizer http://bioub.github.io/dom-visualizer/Reconciliation https://reactjs.org/docs/reconciliation.html3. Getting Started 3.a Picking the development IDE or the Editor To work with code, we need an editor which can provides us the following: An engaging developer experience Notify and spot errors in advance Can perform autocomplete, syntax highlighting and maintain readability of code Easy to customise and provide plugins to help in developer workflow Also provide us flexibility to create our own plugins And help in code collaboration while working with multiple team members. There are various editors available for developers in market such as Sublime, Atom, Brackets and Visual Studio Code & WebStorm IDE.  All of them have their pros & cons.  In our current project we are sticking to Visual studio code. It is available for Windows, Mac and Linux.  You may download the editor based on your operating system https://code.visualstudio.com/3.b Environment Setup To run React we will require Node.js on our operating system. Node.js is written by Ryan Dahl and is based on Chrome V8 engine.  Download Node.js & visit the urlhttps://nodejs.org/en/download/ And we will install the release with even number and LTS (Long term support) We will be installing the Node.js version 12. It also includes npm which we will use to run our first app in React.  To run Node.js we can use command prompt on Windows and use Terminal on macOS.To check the Node.js version, we need to run the following command. node --versionAs you can see from screenshot that we have installed version 12 (v12.18.2) After installation of Node & npm.we will be creating to create a React app with command line interface (CLI). mkdir CodefactoryInstallation of create-react-app I have created a directory called Codefactory.  And in that directory, I am going to run the following command npx create-react-app my-appAfter couple of minutes, the packages will be installed. 4. Quick intro to Node & NPM. In the previous sections we have mentioned the use of Node and NPM. Node.js help developers to use JavaScript as the main language to build their apps. It is open source.  Some of its salient features are: Event driven Non-blocking I/O (input/output) cross platform run time environment Based on Chrome V8 JavaScript EngineRyan Dahl is the creator of Node.js. V8 supports new features of JavaScript and those features are made available to Node.js. And which keep the Node.js in mainstream based on the recent development and upgradation happening in the ecosystem of JavaScript and ECMAScript. Since modularity is much needed and required by developers. Node.js follows the concepts of modules as characterized by NPM. NPM is a package manager for Node.js modules and various packages are available for developers to test and experiment with their code. Official site :  npmjs.comReferences: Node.js Ryal Dahl (2009) https://www.youtube.com/watch?v=ztspvPYybIY5. Your first React app  Start with the boilerplate app Now let's go back to terminal & run our app. We will go to directory my-app and after running the following command cd my-appNow you are in my-app directory, where the npx has downloaded the dependencies and modules.  5.2 File structure of React app Now, we will go to Visual studio code. We will go to menu bar and Add the folder my-app to workspace. In the Visual studio, the explorer will list down the files under the directory structure.  5.3 Run your React app Now is the time to run the React app.  To open terminal go to menu bar and go to Terminal > New Terminal. This will open the terminal at the bottom. We need to type following command in terminal to start the app.  npm start The command line will instruct the app to open in a new browser  http://localhost:3000/So, here we can see the app running. Good job so far!And as per the instructions from screenshot we will open the App.js The App.js will show a bunch of import statements and function App()There are various methods to create React app via CLI such as yarn and npm on local system. In case you are facing problems during installation. As an alternative approach to create a React app, you can check StackBlitz https://stackblitz.com/And create a new workspace of React It will provide you an online playground to tinker and play with the source code in the browser itself. At the left there is a workspace and at the right output from the app. It will show you the index.js which show the import statement, class App component declaration and the render() function. The render function contains JSX. And this allow us to write HTML in JS. This is for a little human friendly version for readability for both experienced programmers and newbie. Reference https://github.com/facebook/create-react-app5.4 Debugging tool React provides the React Developer tools to check and inspect the components created. It is a very handy tool for debugging. To install React developer tools we will open the below url in google chrome and install add-on from chrome web store  https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en Once we have clicked on Add to Chrome, the tool will be installed.  To open the tool go to your project at localhost. And right click it will show the context menu and click on inspectTo open the tool go to Components tab as shown below:6. Tinker and Play Once we have opened the file App.js in our main project created from CLI. We can tinker around and play with the code. On line number 10, We have a paragraph tag. We can choose any message we want to write and see how it appears on the React app. For E.g. I have added this message in Paragraph tag and inside of the paragraph tag there is a right foot icon enclosed in Bigger text tag. Once we save the file, it will auto reload on the app. So, the auto reload feature saves us from manually load the browser when new changes are saved to disk.            A Journey of a Thousand Miles Begins with a Single Step.           Now feel free to introduce your messages, add some tags and play around. I hope this will serve a good starting point for you to learn and practice. Before you acquire the skills to become a React developer, I hope the understanding of HTML, CSS and JavaScript will give you a good foundation. Happy Learning!. Become a pro at Web Development with the help of our  React training courses. Experience Immersive Learning. 
6859
Step-by-Step: Create a React Project From Scratch

Hello learners. In this tutorial we will learn How... Read More

What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return < h1 >{`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root"));Alright. But is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { }, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (    Decrement  {value}  Decrement    );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above component can be implemented as class based component like below:import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return < h1 >{`Hello ${this.props.name}`};  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.Component and its lifecycle In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  React lifecycle. To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser.Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (      -   {count}    +      );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.
6749
What Is a React Component? Write Your First React ...

Prior to ReactJS, Popular frameworks like Angular... Read More

How to Update Document in MongoDB

MongoDB provides the update() method to update the documents of a collection. To update only the specific documents, you need to add a condition to the update statement so that only selected documents are updated. In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. Updating Single document Syntax: db.collection.update(query, update, options) Use the update method  Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. Use the $set operator to update the values  Choose the Field Name that needs to be updated and enter the new values accordingly –  Employee_Name =”Daniel Morales”db.Employees.update( {"Emp_ID" :100}, {$set:{"Employee_Name" :"Daniel Morales"}}); WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })Updating Multiple documents Syntax: db.collection.update(query, update, options) For updating multiple documents at the same time in MongoDB, we need to use the multi option or else by default only one document is updated at a time.The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as "1" and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. Use the update method  Specify the condition which should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. Use the $set operator to update the values  Choose the Field Name(s) that needs to be updatedand enter the new values accordingly – Employee_Name =”Nandan Kumar” Emp_ID = 21db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}})MongoDB save() Method  The db.collection.save() method is used to update an existing document or insert a new document Syntax: db.collection.save() db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({“ nInserted" : 1 })The save() method returns a WriteResult object which contains the status of the insert or update operation. During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:db.Employees.find(); {"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 }In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . Note -  If the document doesn’t contain an _id field, then the save() method calls the insert() method. db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":0,”_id”:2400})The save() method performs an update with upsert: true since the document contains an _id field:  db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 1,  "nUpserted: 1, "nModified":0 })Note -  If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. Updating Single and Multiple Values in MongoDB documents by using methods  -updateOne, updateManywith examples : MongoDB updateOne() method This method updates a single document within a collection matching the filter or condition. Syntax The syntax of updateOne() method is − db.collection.updateOne(, ) Example> db.Employees.updateOne( {First_Name: 'Nandan'}, { $set: { Age: '30',e_mail: 'nandan@gmail.com'}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }MongoDB updateMany() method The updateMany() method updates all the documents within a collection based on the filter or condition . Syntax : The syntax of updateMany() method is − db.collection.updateMany(, ) Example>db.Employees.updateMany(  {Age:{ $gt:"25"}},  { $set:{Age:'12'}}  )  {"acknowledged":true,"matchedCount":2,"modifiedCount":2}Using the find command, you can retrieve the contents of the documents:> db.Employees.find() { "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345 { "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" } { "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update( {type:"FullTime"}, {$set:{salary:20000}}, {upsert : true} )WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   You can also see the upsert getting reflected in the Write Result of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria, then it will perform an update operation or else it will insert a new document into the collection. Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true} . This command works as both updateOne and updateMany command. db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" },    } )Here, it will update only first document which matches the condition.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" },    }, { multi: true } // Additional Parameter )Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition .db.collection.updateOne() --> method to update only one document in a collection.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated      } )This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”. $set operator (called as update operator) updates the value of the bonusEligiblity to False.You can also update multiple parameters but they need to be separated by a comma (,). E.g.$set: { "bonusEligiblity": "False" , “emp_status : ”New”},db.collection.updateMany() --> method to update multiple document in a collection matching the specified conditiondb.Employees.updateMany(    { "joinYear": "2020" },   { $set: { "bonusEligiblity": "False" },   } )Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update(     {type:"FullTime"},     {$set:{salary:20000}},     {upsert : true}  )WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":1 })  You can also see the upsert getting reflected in the WriteResult of the above operation.upsert operation in MongoDB is used to save documents into collection.If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.upsert  also partially updates an object in MongoDB so that the new object will overlay or merge with the existing one.In brief, upsert is also used to update a document with the contents of another document, but only updates the fields that are absent and completely ignore the fields that are already set.ConclusionTo summarize, MongoDB has methods: update() and save() which are used to update documents into a collection. The update() method updates the values in the existing document while the save() method is used to insert a new document or update an existing document if it already contains an _id field The parameters in the document.update() method is a condition for which document needs to be updated, and the next is the update operation which needs to be performed. db.collection.update (query, update, options) In this article, we have gone over the update() method, save () method, updateOne() method and updateMany() method with examples for each. We have also explored the upsert function. Hope this has been useful. The MongoDB course will get you familiar with the popular NoSQL database and arm you with the essential skills to start using Mongo to power your software application. Happy coding! Your one-stop-shop for MongoDB is just a click away. Access our live online training and find easy solutions to all your queries here.
8023
How to Update Document in MongoDB

MongoDB provides the update() method to update the... Read More