MERN
Tags: javascript, mern, fullstack
Published: 2019-10-18 17:46:13

---
title: MERN
published: true
description: This post is an ever-growing document. It goes along with FullStackOpen's curriculum. As I make progress through their course, I will share my knowledge here.
tags: javascript, mern, fullstack
---

| Symbol | Description                                        |
| ------ | -------------------------------------------------- |
| 💡     | Project developed in order to understand a concept |
| 📕     | Project is no longer maintained                    |
| 👶     | Project content is not updated regularly           |
| 📝     | Project is based on an exercise from a book        |
| 🔥     | My favorite projects                               |
| Source | [Repository](https://github.com/tpkahlon/express)  |

| Project Title          | Project Link                                                                                                                    |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Basics                 | Express API concepts                                                                                                            |
| Fake Team              | Fake Team handles all CRUD operations for REST API. It enables input validation using Joi.                                      |
| Rest API with Mongoose | ES6 compatible code structure of REST API with CRUD operations                                                                  |
| Share Idea             | Simple React Application built on basic REST API and MERN stack: [Demo](https://go.aws/34QbTQl)                                 |
| Bakery Store           | Web site built using Express                                                                                                    |
| Share Projects         | MERN site to add, edit, delete, view Project links: [Demo](https://share-projects.herokuapp.com/)                               |
| Muft                   | An online application to listen to free radio stations : [Demo](https://muft.herokuapp.com/)                                    |
| Google Images Search   | An online application to scrape 100 google images based on timing filter : [Demo](https://google-images-scraper.herokuapp.com/) |

Current Status: Chapter 3(a) in progress...

## Jargon

- FSO: Full Stack Open
- Client: Local user device
- Server: Host machine where site is stored

This post is a living document. It will get updates as I proceed through University of Helsinki's curriculum. It will serve as a complete documentation of my journey/experience/knowledge achieved from the course.

- Course: [Link](https://tiny.cc/fsoen).

## History

The motivation behind this post is to turn my creative idea into a full-stack web application. From this germination of seed, arisen the need for the tools. Hence, I researched and came across FSO's curriculum which captured my interest.

## Motivation

My purpose behind this post is to share my knowledge while I learn core principles and put them in practice. As you follow along with this post, you may have to come up with your motivation factor, that will bind your interest in learning full-stack development principles.

## Timeline

No bells and whistles. This post strictly focuses on serious learning. No hard timelines associated. Follow the post at your own pace and I will make updates here whenever I complete a theoretical module and fully understand the topics at hand.

## Fundamentals of Web Applications

### Requirements

- Install Google Chrome and Firefox
- Learn how to use Developer tools in each browser (especially Network tab, Console tab, Inspector/Elements tab)

### Client/Server Communication

- Reference Project: [Link](https://fullstack-exampleapp.herokuapp.com).

While you open link above, Keep Network tab open in developer tools. Check Disable cache option. Each time you reload the link above, client will send an explicit request to server for each asset if "Disable Cache" is checked: [Link](https://devtoolsecrets.com/secret/performance-disable-the-browser-cache.html).

Client communicates with Server using `HTTP` protocol: [Link](https://developer.mozilla.org/en-US/docs/Web/HTTP).

Network tab is place where you can see the entire process in action. Reload the page and you will see two HTTP requests were sent to the server, one for the HTML page and other for the Image with response 200.

When you click each request, you can see more options like Request headers, Request response, HTTP header information, Cookies, Params, Type of HTTP request (200/404) etc.

In response header, you can view entire HTML page. This page contains an image tag which initiates another GET request from client to fetch image content from server.

In Firefox, you will see an additional 404 GET request for missing `favicon.ico` file in meta tags.

#### HTTP Cycle

From above reference project, we can easily prototype a cycle of HTTP requests as follows:

- BROWSER
- HTTP GET Request (https://fullstack-exampleapp.herokuapp.com)
- SERVER
- HTML code
- BROWSER
- HTTP GET Request (https://fullstack-exampleapp.herokuapp.com/kuva.png)
- SERVER
- Image
- BROWSER
- Renders the page in the browser.

### Traditional web applications

Traditional web applications involved putting business logic on the server which generated HTML pages and added certain dynamic content in those pages which got parsed on the client side like PHP, ASP. In FSO's [Referenced Project](https://fullstack-exampleapp.herokuapp.com)., Express is running on the server which generates HTML page that gets loaded on the client. Number of notes is a dynamic content in HTML file whose logic resides on the server.

### Running application logic on the Browser

In FSO's [Reference Project's Notes](https://fullstack-exampleapp.herokuapp.com/notes) page, all the business logic for this page is written on the client side. When you load this page in the browser, see the Network tab to understand pattern of HTTP communication. Client makes a request to Notes page on the server, server return HTML page, which further contains a `CSS` file, `JavaScript` file. Within the `JavaScript` file, there is an AJAX method used to further request for `JSON` file. HTTP requests are triggered to get all these assets. Once `JSON` file is retrieved, JavaScript file runs the logic that generate DOM elements which get appended to the document.

### Event Handlers and Callback Functions

Event handlers and Callback functions are common occurrences in JavaScript. A certain block of code written as a Function, is bound to an event, which gets executed when that particular event happens.

In Notes page, `JavaScript` file had certain logic where `onreadystatechange` is an event bound to an event listener function.

- Callback function: [Link](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function).

### Document Object Model

In Chrome's Element tab and Firefox's Inspector tab, you can see tree structure for the entire DOM. In Notes page, we observed `JavaScript` file had certain logic that create and add HTML Nodes into DOM tree.

- DOM: [Link](https://en.wikipedia.org/wiki/Document_Object_Model).

### Manipulating DOM from Console

The top-most node in DOM tree is `document`. Let's try an example in Console tab to manipulate DOM.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/f5uqv830).

### CSS

Notes page has certain styles associated that are present in `main.css` stylesheet.

### Loading a Page containing JavaScript - Revised

HTTP communication pattern for Notes page is as follows:

- BROWSER
- HTTP GET Request (https://fullstack-exampleapp.herokuapp.com/notes)
- SERVER
- HTML code
- BROWSER
- HTTP GET Request (https://fullstack-exampleapp.herokuapp.com/main.css)
- SERVER
- Stylesheet file
- BROWSER
- HTTP GET Request (https://fullstack-exampleapp.herokuapp.com/main.js)
- SERVER
- JavaScript file -> File execution happens on BROWSER
- HTTP GET Request (https://fullstack-exampleapp.herokuapp.com/data.json)
- SERVER
- JSON file
- BROWSER
- Renders the Notes page in the browser.

### Forms and HTTP POST

In Notes page, there is a Form tag in the markup that takes in user input, triggers a POST request upon submission to the server. Server takes the parameters came along with the request, creates an object, adds them in the array and redirects user back to Notes page. See Network tab to investigate the whole process.

### AJAX

Notes page uses traditional AJAX approach to get notes data.

- AJAX: [Link](https://en.wikipedia.org/wiki/Ajax_programming).

### Single Page Application

See the revised version of Notes app below, in SPA format. Investigate it using Network tab. The key takeaway is that upon submission, form does not reload the page and HTTP POST is handled in JavaScript file.

- Demo: [Link](https://fullstack-exampleapp.herokuapp.com/spa).
- SPA: [Link](https://en.wikipedia.org/wiki/Single-page_application).

### References (Chapter: 0B)

- HTML: [Link](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics).
- CSS: [Link](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics).
- Forms: [Link](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form).
- Vanilla JavaScript: [Link](https://www.freecodecamp.org/news/is-vanilla-javascript-worth-learning-absolutely-c2c67140ac34/).
- Front/Back Ends: [Link](https://en.wikipedia.org/wiki/Front_and_back_ends).
- JS Fatigue: [Link](https://auth0.com/blog/how-to-manage-javascript-fatigue/).
- JS Fatigue (2): [Link](https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4).

### Key Takeaways

- Understand Traditional application behaviour vs. Single page application behaviour
- Understand function of legacy concepts like AJAX
- Understand HTTP communication between Client/Server using Network tab
- Understand Event handling, Callback functions, DOM, HTTP Status Codes.

## Introduction to React

### Create-React-App

Use `yarn create react-app test` to scaffold a new React project.
Use `yarn start` to run development environment.

- Source: [Link](https://github.com/facebook/create-react-app).
- Arrow Functions: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
- Components: [Link](https://reactjs.org/docs/components-and-props.html).
- ES6: [Link](https://es6-features.org/#Constants).
- JSX: [Link](https://reactjs.org/docs/introducing-jsx.html).
- Babel: [Link](https://babeljs.io/repl/).

### Component

Following is an example of a React component. You can run JavaScript logic inside of it. **JSX** syntax was used to return a block. JSX is compiled into ES2015 syntax using Babel.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/2ug14ce6).

### Multiple Components

Following is an example of multiple react components.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/gjsuqm6d).

### Props: Passing data to components

Props are used to pass data to components. See example below. We used ES6 destructuring to get specific parameters passed to child component from parent component.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/0d8m3tbh).

#### Notes

- React component names must be capitalized.
- Use console.log() to debug errors.
- React component must contain one root element.
- Fragments can be used to wrap multiple elements.
- Fragments: [Link](https://reactjs.org/docs/fragments.html#short-syntax).

### Key Takeaways

Get familiar with ES6, JSX, Components, Props, Multiple Components, Components rules, Fragments.

### Minor Project

Based on current concepts we covered in `FSO`, I have built a Create-react-app project which allows user to track/view current Events hosted by Toronto library. The source code for this project is up on Github for your reference. There were some key milestones I achieved during this project. I was able to perform pagination behavior where we you press Load More button at the bottom of App, you merge next set of data into your existing objects. I used `Lodash` library functions like `chunk`, `sortBy` that were helpful to achieve some tasks in this project. Front-end portion of the project is coded using `React bootstrap`.

Some of the concepts like `useState` and `useEffect` were not covered yet. Do not worry about it, focus mainly on separation of concerns like declaring child/parent components, passing props and keeping business logic separate. I will make frequent updates to divide the components into clean nuclear modules with proper naming conventions.

- View: [Link](https://tpkahlon.github.io/tpl-events).
- Source: [Link](https://github.com/tpkahlon/tpl-events).

I would encourage you to build a similar starter app to practice some of the React components we covered so far in `FSO` curriculum.

## JavaScript

Modern JavaScript is updated under ECMAScript standards. Modern JavaScript code is converted into legacy code via Babel. NodeJS allows to run JavaScript out of the scope of browser environment.

### Variables

`Let` allows you to define a variable and change it later. `Const` does not allow program to change a variable when it is set. `Var` declaration is deprecated.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/3aucg4xe).

### Arrays

Arrays allow us to hold any type of data in it.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/jxc2pz94).

### Array Mutation

To append an item to existing array and clone resulting array in React realm, Use `concat`.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/7drjLhuc).

### Destructuring

To store the array item in individual variables, use destructuring operator.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/hsumx9co).

### Objects

Object can store key-value pairs where value can be of any data type.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/6L2rpa18).

### Functions

- Example Project: [Link](https://jsfiddle.net/tpkahlon/kh2ewuos).

Concept of Classes / THIS will be discussed in depth during later part of course.

- ES: [Link](https://en.wikipedia.org/wiki/ECMAScript).
- Babel: [Link](https://babeljs.io).
- Const: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const).
- Let: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let).
- JavaScript: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript), [Link](https://github.com/getify/You-Dont-Know-JS), [Link](https://egghead.io), [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript).
- THIS: [Link](https://egghead.io/courses/understand-javascript-s-this-keyword-in-depth).

## Component state, Event handlers

### Component helper functions and Destructuring

Component helper functions are logic blocks whose output is rendered by the component. See `calculateRun` function below.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/ek8vs43t).

### Page re-rendering, Stateful component and Event handling

- Example Project: [Link](https://jsfiddle.net/tpkahlon/kzc0d74b).

## A more complex state, debugging React apps

### Complex state

Use object to contain multiple state properties. Make use of ES6 spread operator to concatenate original value of state and new state value achieved.

- Spread operator: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
- Example Project: [Link](https://jsfiddle.net/tpkahlon/p698x5La).

### Handling arrays

- Concat: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat).
- Push: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push).
- Join: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join).
- Example Project: [Link](https://jsfiddle.net/tpkahlon/vebwyz28).

### Conditional rendering

- Example Project: [Link](https://jsfiddle.net/tpkahlon/Lkef902s).

### Debugging React applications

- Use developer console for error debugging.
- Use `debugger` command in your code.

### Rules of Hooks

Do not use `useEffect` and `useState` inside a loop, conditional expression or inside another component.

### Event Handling Revisited

Event handlers must always be a function or a reference to a function.

- Example Project: [Link](https://jsfiddle.net/tpkahlon/Lkef902s).

### Passing Event Handlers to Child Components

- Example Project: [Link](https://jsfiddle.net/tpkahlon/mwhrjsf9).

### Do Not Define Components Within Components

- Never define components inside of other components.
- Make each component into its nuclear entity.

## Rendering a collection, modules

### Developer Toolkit

- Get comfortable using `console.log()` whenever an issue persists.
- VS Code Snippets: [Link](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_creating-your-own-snippets).
- React Snippets: [Link](https://marketplace.visualstudio.com/items?itemName=xabikos.ReactSnippets).

### Higher Order Functions

- [Learn the concept](https://www.youtube.com/watch?v=BMUiFMZr7vk&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84).
- [Map](https://www.youtube.com/watch?v=bCqtb-Z5YGQ&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84&index=2).
- [Reduce](https://www.youtube.com/watch?v=Wl98eZpkp-c&t=31s).

### Rendering Collections

- Example Project: [Source](https://github.com/tpkahlon/notes).
- Array indexes as keys: [Link](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318).
- Import: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import).
- Export: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).

## Forms

- Example Project: [Source](https://github.com/tpkahlon/notes).
- Controlled Components: [Link](https://reactjs.org/docs/forms.html#controlled-components).
- Conditional Operators: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).

## Getting data from server

- Example Project: [Source](https://github.com/tpkahlon/notes).
- JSON Server: [Link](https://github.com/typicode/json-server).
- Promise: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
- Asynchronous Loop: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop).
- Event Loop: [Link](https://www.youtube.com/watch?v=8aGhZQkoFbQ).
- Axios: [Link](https://github.com/axios/axios).
- State Hooks: [Link](https://reactjs.org/docs/hooks-state.html).
- Effect Hooks: [Link](https://reactjs.org/docs/hooks-effect.html).
- Effect Procedure: [Link](https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect).

## Altering data in server

- Example Project: [Source](https://github.com/tpkahlon/notes).
- JSON Server: [Link](https://github.com/typicode/json-server).
- Promise: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises).
- Promise Chaining: [Link](https://javascript.info/promise-chaining).
- Catch: [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch).

## Adding styles to React app

- Example Project: [Source](https://github.com/tpkahlon/notes).
- className: [Link](https://reactjs.org/docs/dom-elements.html#classname).
- DOM style: [Link](https://reactjs.org/docs/dom-elements.html#style).
- Inline styles: [Link](https://react-cn.github.io/react/tips/inline-styles.html).

## Goodies

### Yarn

- Docs: [Link](https://yarnpkg.com/en/docs/cli/).
- Initialize a project: `yarn init -y`.
- Add a dependency: `yarn add package_name`.
- Add a development environment based dependency: `yarn add package_name --dev`.
- Add a global dependency: `yarn global add package_name`.
- Check outdated dependencies: `yarn outdated`.
- Remove a dependency: `yarn remove package_name`.
- `yarn-lock.json` is an important file and do not ignore it in the repository.
- Clean global cache: `yarn cache clean`.
- Run audit: `yarn audit`.