Skip to content

Instantly share code, notes, and snippets.

@r-kohale9
Last active March 15, 2021 18:10
Show Gist options
  • Save r-kohale9/e9862646e63be76bb52be6c7de901d94 to your computer and use it in GitHub Desktop.
Save r-kohale9/e9862646e63be76bb52be6c7de901d94 to your computer and use it in GitHub Desktop.
Summary / Important points from the course codeWithMosh - Mastering React

React Summary Points

Library's - All the installed files are stored in node_modules folder.

Boostrap

  • npm i bootstrap@4.1.1
  • import 'bootstrap/dist/css/bootstrap.css';

Font-Awesome

  • npm i font-awesome@4.7.0 // different font and symbol can be rendered
  • import 'font-awesome/css/font-awesome.css';

Loadash

  • npm i loadash@4.17.10
  • import _ from 'loadash' // _ because loadash is a optimised version of library Underscore

Prop-Type

  • npm i prop-type@15.6.2 // used for type-checking
  • import PropTypes from 'prop-types';

rrd-React Router Dom

  • npm i react-router-dom@4.3.1
  • import {BrowserRouter} from 'react-router-dom';
  • import {Route, Switch , Redirect, Link} from 'react-router-dom';

Query-String

  • npm i query-string@6.1.0
  • import queryString from 'query-string'; //used for parsing props.location.search

Joi Browser

  • npm i joi-browser@13.4
  • import oi from 'joi-browser';

Axios

  • npm i axios@0.18 //used for connecting to backend
  • import axios from 'axios';

Toastify

  • npm i toastify@4.1
  • import { ToastContainer } from 'react-toastify';
  • import 'react-toastify/dist/ReactToastify.css';

Raven

  • npm i raven-js@3.26.4
  • import Raven from 'raven-js';

Jwt-decode

  • npm i jwt-decode@2.2.0
  • import jwtDecode from 'jwt-decode';

Code Editor Extension To Be Installed

  • Simple React Snippets
  • Pritter (Enable formatting on save.)
  • Auto Import-ES6,TS,JSX,TSX

Shortcuts Open -

  • Console - ctrl+shift+i
  • Refactoring - ctrl+shift+r
  • Wraper - ctrl+shift+p

Links

  • getbootstrap.com
  • fontawesome.com/v4.7.0
  • reactjs.org // Under doc/Advanced guides/Type checking with prop types //(prop-types methods)
  • reacttraining.com/react-router // Documentation for react-router
  • npmjoi.com
  • jsonplaceholder.typicode.com // Provide fake REST API (Representational State Transfer Application Programming Interface) endpoints (i.e fake backend)
  • sentry.io/welcome/
  • Programmingwithmosh.com/tools/ // Provides 2 months of free sentry at 50$ month something.
  • jwt.io
  • mlab.com
  • git-scm.com

Chrome extensions

  • React Developer Tools- for the purpose of Debbugging.
  • Json view - for proper formatting of json data.
  • Postman - for talking to the backend i.e GET && POST data

React

React - Reacts to state change.

Angular or React?

Angular
  • Framwork -> Complete Solution.
React-
  • View library - Renders view and checks if it is in sync
  • Very small API
  • A lightweight library for building UI's.

Use following to create an app.

$ sudo npm i -g create-react-app@1.5.2

- 08 - Special keywords

1 - Let/const

Use -

  • var->function,
  • let->block,
  • const->block,
  • use mostly const and when u need to resign use let

2 - Objects

  • Function as a member of object is said to be a method

3 - this

4 - Arrow function

  • Don't need to bind the 'this' keyword while using the arrow function.

5 - Destructuring

6 - Spread

  • by using concat() the code get complicated

7 - classes

  • Uses Pascal naming convention

8 - Modules

Important Topics w.r.t to lesson

- 15

const colors=['red','blue','green']
const items = colors.map(color=>`<li>${color}</li>`)
console.log(items)
Literals
<li>${color}</li>
  • This is called template literals (To understand literals refer 'js beginers course'.).
  • '$' - Sign indicates a up coming as argument.

To use inheritance simply use the extends keyword. Whenever a constructor is used super() keyword should be included in its child class.

- 21

Class is not usually an object but in Js it is. if we use

export default class Teacher{}

while importing teacher in other file you use:

import Teacher from './filename'

because it is default export if it weren't default i.e named, you would have used:

import { Teacher } from

Default -> imp ... from '' Named -> imp {...} from ''

- 24

Organisize all your file such that you end up storing all the components files in the components folder and use "Camel" i.e 'loginForm' notation while naming the files and use '.jsx' for better practise.

- 25

A class cannot return two tag side by side i.e

return (
  <h1>A</h1>
  <h2>B</h2>
)

this will give an error because what React does is it complies it as

React.createElement('div')

and with two tags it doesn't know what to do, so simply insert both this tag inside a:

'<div>...</div>'

This will get rid of the error. Or you could insert them inside of:

<React.Fragment>...</React.Fragment>

both the methods are valid use anyone.

- 26

In React

state={}

is the object that stores all the data the class/component is going to use.

  • To generate a random photo use 'https://picsum.photos/'
  • If you want to add your own to the default className use
style = { this.styles }

as attributes to overide the default's of the bootstrap.

  • To use Refactoring use the shortcut 'ctrl+shift+R' what this does is extracts the selected lines and makes them a newMethod().

- 29

To render lists use the map() it is similart to loops, map() need a unique key for each iteration.

- 30 - Conditional Rendering

i/p {true && 'hi'}
o/p ->hi
i/p {true && 'hi' && 1}
o/p -> 1

- 30

Dom-events

  • onKeyDown, onKeyUp, etc
  • onClick, onDoubleClick, etc and etc

- 35

Whenever you need to pass an argument to a event handler use arrow function and in the body of the function simply pass the event handler and the argument. this needs proper explanation***********

- 36

Whenever you create a new React app you need to re-install the librarys. Just to make sure you have everything up and running.

- 38

Zen-coding

- 48

The component that owns the piece of state should be the one modifying it. this needs proper explanation************

- 56

Lifecycle Hooks - Hooks that allow us to enter into the Lifecycle of the Dom and do something with them.

1.Mount-Instance is created and inserted into the Dom

  • constructor
  • render
  • componentDidMount

2.Update-When state or props gets changed

  • render
  • componentDidUpdate

3.UnMount-When component is removed from the dom

  • componentWillUnmount

This are the most used Lifecycle hooks their are more but won't use them.

- 57

MOUNT is called ONCE. When using MOUNT the state should be set directly i.e

this.state = this.props.something;

and not

this.setState()

this will give an error.

  • componentDidMount is called after the component is rendered into the Dom so that we can use AJAX calls to get data from the server setState should be used.

  • Lifecycle can only be used in the classes and not in Stateless functional component.

  • App components and all its children are rendered recursively.

  • componentDidUpdate - This method is called after a component is updated.

  • componentWillUnmount - This method is called just before a component is deleted/removed from the Dom so that we can remove the data not leaving any memory leaks.

- 63

To show a hand cursor while howering over a component use the attribute:

style = {{ cursor:"pointer" }}

- 68

loadash is used to get an array such that we can:

[1 ... pageCount].map()

- 70

Paginate is the function that return the array of movies to be loaded on that page or currentPage.

export function paginate(items, pageNumber, pageSize) {
  const startIndex = (pageNumber - 1) * pageSize;
  return _(items)
    .slice(startIndex)
    .take(pageSize)
    .value();
}

We apply slice and take the array that should be an loadash object so to convert it, we use _(items) futher is self explanatory and value is used to convert it back to a regular array.

- 71 - propTypes

Used as:

Pagination.propTypes = {
  itemsCount: PropTypes.number.isRequired,
  pageSize: PropTypes.number.isRequired,
  currentPage: PropTypes.number.isRequired,
  onPageChange: PropTypes.func.isRequired
};

If error is found, error is shown in console, and also gives some kind of type-documentation to your code.

- 73

The reason the movies, genders are an empty array because sometimes it takes time to get the data from backend and if the movies and generes are found undefined we might get an run-time error.

- 75

ListGroup.defaultProps = {
  textProperty: "name",
  valueProperty: "_id"
};

This are the default props that u dont need to write this props while using ListGroup component. Whenever the state is updated the component and all its children are re-rendered.

- 94 - react-router

Adding Routing to the app

Wrap the

<App/>

tag with

<BrowserRouter></BrowserRouter>

What this does is this component wraps the history objects and passes it down to component tree, so anywhere in the component tree we will be able to use the histroy object. To add a route use ->

import { Route , Switch , Link } from 'react-router-dom';

this has two attributes->

  • path
  • component

if 2 routes match for same route than both of them is loaded. To get rid of this add

exact

as an attribute OR you could simply use the

<Switch>...</Switch>

tag wraping all the paths/routes in between this tag. While using Switch you should arrange them routes from most specific to most generic ones.

To prevent re-downloading of the files that have already been downloaded once use

<Link>...</Link>

for all the href use Link tag because it not have 'href' it uses 'to'. What it does is prevents the default action.

- 98

To pass props to Route use render instead of component and equal it to an arrow function inside whick declare the component tag along with the props.

<Route path='' render={ props => <Products onSort={} { ...props } /> }

props is included so that the histroy, loaction props are also included.

- 100

Parameters in routes can be used as

to=/products/:id
to=/posts/:year?/:month?

this is a regular expressions when you append ? it means that,that parameters are optional in this case both are optional.

- 101 - queryString

- 107

Zencoding does not work on .js file it works on .jsx

- 109

To extract anything from the url such as the id use props or Destructuring as

{ match }
<h1>{ match.params.id }</h1>

- 112

Cool Zencoding Trick -> So if you want to wrap a tag with another tag select the text and press 'ctrl+shift+p' then type Wrap with Abberviation. The type the tag you want to wrap with such as div. You can also Zencode here.

- 113

So to prevent full reload of the Form tag we say it has a onSubmit attribute set to this.handleSubmite.

handleSubmit= e => {
  e.preventDefault();
  //Call the server
}
<Form onSubmit={this.handleSubmit}/>

- 114 - Accessing a element in Form

Wrong way to access Dom elements in react-

const username = document.getElementById("username").value;

because we don't access the document directly in react otherwise it wont be easy to maintain the code. But if you really need to access dom element.

  • First create a reference such as->
    • username = React.createRef();
  • add attribute
    ref={this.username}
    to the input tag whose ref you been trying to create.
    const username = this.username.current.value;

Now if you need to focus on this element.

  • Create a Lifecycle hook -->>

    componentDidMount(){
      this.username.current.focus();
    }
  • This will get the input field selected.

  • There is a better way ---->>>> Just use

    autoFocus

    attribute and save yourself the trouble.

- 116

While working with the properties of an object always use bracket notation [] and not the dot notation.

- 119

Finding something in an array ->

  errors.find(e => e.name ==== 'username')

- 120

Understanding validations basic.

- 123 - joi-browser

validate = () = {
  const result = Joi.validate(<objectThatYouWantToValidate>, this.schema, { abortEarly: false });
  if(!result.error) return null;

  const errors={};
  for (let item of result.error.details) error[path[0]] = item.message;

  return errors;
}

By default Joi terminates as soon as it find an error called as 'Abort Early'.

- 129

  • To simplify any code just extend them to another class/component and write all the componenets as functions with corresponding inputs.
  • If few attribute are in the form of
    name = {name} id = {id}
    and the props are destructered as 'name', 'id' etc. Then remove such props and use
    ...rest
    as destructured and
    {...rest}
    as attributes.

- 135

Controlled elements cannot be null they can be an empty string. While uncontrolled elements can be null.

- 137

Operations such as creating, reading, updating, deleting are called as CRUD operations.

- 138

Librarys to connectiong to backends :

  • Fetch API
  • jQuery AJAX
  • Axios

- 139

The best place to get data from backend is in Lifecycle Hooks i.e

componentDidMount(){
  const promise = axios.get('url')
}

To get data from a httpresponse use promise.then() which is considered a poor way. A better way is to await the asyncronous request/promise. Whenever you use await in that function you should async that function.

- 140

Posting data to the server.

const { data: posts } = axios.post(<apiEndPoint>, obj);

- 142

You can update data on server using put or patch as follows -

  post.title = 'UPDATED';
  await axios.put(apiEndPoint + '/' + post.id, post)
  await axios.patch(apiEndPoint + '/' + post.id, { title: post.title })

- 145

Expected (404: Not-Found, 404: Bad Request) - CLIENT error

  • Display a specific error message

Unexpected (network down, server down, db down, bug)

  • Log them
  • Display a generic and frindly error message

Use a

try{
  ...
} catch (ex) {
  ...
}

to deal with an anticipated error or response errors.

- 146

For handling of unexpected errors use the axios.interceptor.

axios.interceptor.response.use(<'success' in this case 'null'>, error => {
    if in the range then log the error and return Promise.reject(error)
  })

Look at the vid.

- 148

To store the url of the backend or the apiEndPoint create file 'config.json'->

  {
    "apiEndPoint":""
  }

- 149 - react-toastify

import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css'; //app.js

Use the tag in the render as

<ToastContainer/>

Then go to httpservice or wherever you used alert use->

import { toast } from 'react-toastify';

instead of alert("..."); use

toast.error("...");

or

toast.success("...");

or

toast.info("");

You can use it also as a function and call it as

toast("");

- 150

Whenever a error is encounterd it is logged on to the users console which we don't have access to so we use loging as a sevice provider. We will be using 'Sentry'.

How to use raven look at the vid. Where ever you are using console.log() use

Raven.captureException();

- 151

Create a seprate file for logging service and define them under different function so whenever you decide to change the logging service you will have to make changes to the single file only.

- 155

To add backend to the project->

  • copy the backend folder next to the project folder
  • install the dependencies using
    cd && 'npm i'
  • now we need to see our database and some sample data so run
    node seed.js
    
  • Now if you open up mongodb compass u will see the database
  • Finally start your server 'node index.js'

- 156

Postman Chrome While talking to the backend through Postman you might endup with status 401 UnAuthorised. (This is something you should not do in the production environment)

  • Stop the backend
  • Open backend
    $ cd config 
    
  • open default.json
    "requiredAuth":false
    $ node index.js
    

- 159

You cannot spread a pormise you should first await it and store it in a const then spread that const.

- 163

Whenever you use await on a promise always destructure it to get the data property while storing the data. (Just a thumb rule)

- 165

While updating or saving the data if it consists an property of id while exists in the body as well as in the url then you should remove the id from the body cause it won't understand which id to use.

- 171

To manange Authentication sessions use the apiEndPoint + '/' + auth. After POST ing a valid username and password i.e valid data to this api you'll recieve a JSON Web Token (JWT).

- 174

We need to store the JWT for that we use the localstorage, this item has many useful objects such as setItem, removeItem, clear, getItem, key ->

localstorage.setItem('<key>', '<value>')

- 175 - Logging the custom header to console

To dynamically set the token after registeration we need to access the 'x-auth-headers' and set it to the->

localstorage.setItem("token", response.headers["x-auth-headers"]);

Stop the backend server

$ cd service && open user.js

under router.post you see .header("x-auth-header", token) so inorder for the client to read this header we must set an additional header that is a standard http header so

.header("access-contol-expose-headers", "x-auth-header")

Re-Start the server.

- 177 - jwt-decode

- 178

this.props.history.push("/");

This will take the user to homepage and not reload

window.location = "/";

- 181

With the library called node-mon you don't have to restart the server while making changes to backend.

- 182

Whenever you want to make http request make sure to include this headers->

axios.defaults.headers.response.common["x-auth-token"] = auth.getJwt();

'common' means all kinds of requests such as POST, GET etc you could simply use 'post' or 'get' instead of common.

- 191

You can have environment specific variable as by creating a nameless file .env.development or .env.production. So in this file we will store all our environment variables, all this variable have a key and a value->

APP_NAME_NAME = Vidly in dev
REACT_APP_VERSION = 1

- 192

$ npm run build

This is going to create an optimised production build.

$ sudo npm install -g serve

This is a simple light weight web server.

$ sudo serve -s build

With this command you can serve the content of this build folder.

- 193

After installing heroku to check type 'heroku -v'

$ heroku login

Enter email-id and password with which you have an account on heroku. If this step fails on your machine, if your behind a firewall that require a use of proxy to connect with externl http services if thats the case you need to set an environment variable->

$ export HTTP_PROXY = http://proxy.server.com:1234

Then try login one more time.

- 194

watch

- 195

$ install git from git-scm.com

create a file in the backend .gitignore for what file needs to be ignored while uploading to git and insert node_modules/. run

$ git init

this will initilise a git in this folder.

$ git add

this will stage all our file to commit to the repository

$ git commit  -m "Initial commit"

- 195

$ heroku create 

by leaving it empty it will get a random name. Now to upload the code we have in our local git repository to this so obtained url we use

$ git push heroku master
$ heroku open

this will open the website and you will se an application error.

- 197

To view the heroku logs use the terminal

$ heroku logs

- 198

Watch

- 201

Don't aim for the perfect software Focus on building quality software and delivering it on time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment