Menu

FullStack November 23 Evening

FullStack November 23 Evening

Scratchpad #1 and #2

console.log('Hello World');

let greeting = 'Hello World, Welcome to RST Forum.';

greeting.toUpperCase().toLowerCase();

Scratchpad #3

// let age = 15;

// if (age >= 65) {
// 	console.log('Drinks are free');
// } else if (age >= 21) {
// 	console.log('You can enter and drink');
// } else if (age >= 18) {
// 	console.log("You can enter but you can't drink");
// } else {
// 	console.log("You can't enter");
// }

// if (age % 2 === 0) {
// 	console.log('Even number');
// }

// let password = 'hello world@123';

// if (password.length >= 6) {
// 	if (password.indexOf(' ') !== -1) {
// 		console.log('Password cannot contain spaces');
// 	} else {
// 		console.log('Valid password');
// 	}
// } else {
// 	console.log('Invalid password');
// }

// let loggedInUser = null;

// if (loggedInUser) {
// 	console.log('Here is the content');
// } else {
// 	console.log('Please login to view this content');
// }

// let age = 80;

// if (age >= 18 && age < 21) {
// 	console.log("You can enter but you can't drink");
// } else if (age >= 21 && age < 65) {
// 	console.log('You can enter and drink');
// } else if (age >= 65) {
// 	console.log('Drinks are free');
// } else {
// 	console.log("You can't enter");
// }

// let day = 4;

// if (day === 1) {
// 	console.log('Monday');
// } else if (day === 2) {
// 	console.log('Tuesday');
// } else if (day === 3) {
// 	console.log('Wednesday');
// }

// let day = 24;

// switch (day) {
// 	case 1:
// 		console.log('Monday');
// 		break;
// 	case 2:
// 		console.log('Tuesday');
// 		break;
// 	case 3:
// 		console.log('Wednesday');
// 		break;
// 	case 4:
// 		console.log('Thursday');
// 		break;
// 	case 5:
// 		console.log('Friday');
// 		break;
// 	case 6:
// 		console.log('Saturday');
// 		break;
// 	case 7:
// 		console.log('Sunday');
// 		break;
// 	default:
// 		console.log('Invalid day code');
// }

// let num = 11;

// if (num % 2 === 0) {
// 	console.log('Even');
// } else {
// 	console.log('Odd');
// }

// num % 2 === 0 ? console.log('Even') : console.log('Odd');

let statusMsg = 'online';
// let color = null;
let color = statusMsg === 'offline' ? 'red' : 'green';

// if (statusMsg === 'offline') {
// 	color = 'red';
// } else {
// 	color = 'green';
// }

console.log(color);

Scratchpad #4

// let movs = [
// 	'Avengers',
// 	'Mission Impossible',
// 	'Black Panther',
// 	'The Godfather',
// 	'Race 3',
// 	'Alien',
// 	'Black Panther',
// 	'Avengers',
// ];

// console.log(movs.join(','));

let product1 = ['iPhone 14', 'Apple', 500, 100000, 'Some description...', true];
let product2 = ['Nord 2', 'One Plus', 30000, 1000, 'Some description...', true];

// let products = [product1, product2];
console.log(product1[0]);

let product3 = {
	brand: 'Apple',
	inStock: 500,
	description: 'Some desc...',
	price: 100000,
	name: 'iPhone 14',
	exchangeAvail: true,
	100: 'hello',
	'hello world': true,
};
console.log(product3.price);

Scratchpad #5

// // let arr1 = [1, 2, 3];
// // let arr1 = { 0: 1, 1: 2, 2: 3, length: 3 };

// // const playlist = [
// // 	{
// // 		trackName: 'Song #1',
// // 		trackLength: 3.52,
// // 		album: 'Album #1',
// // 		artists: [
// // 			{
// // 				name: 'Person 1',
// // 				age: 30,
// // 			},
// // 		],
// // 	},
// // 	{
// // 		trackName: 'Song #1',
// // 		trackLength: 3.52,
// // 		album: 'Album #1',
// // 		artists: ['Person 1', 'Person 2'],
// // 	},
// // ];

// // const student = {
// // 	firstName: 'John',
// // 	lastName: 'Doe',
// // 	frameworks: ['ReactJS', 'Express.js'],
// // 	levels: {
// // 		backend: 50,
// // 		frontend: 45,
// // 		data: 5,
// // 	},
// // };
// // console.log(student.levels.data);
// // console.log(student.frameworks[1]);

// // for (let i = 0; i < 10; i++) {
// // 	console.log(i, 'Hello World');
// // }

// // for (let num = 1; num <= 10; num++) {
// // 	console.log(`${num}*${num}=${num * num}`);
// // }

// // for (let i = 100; i > 0; i -= 10) {
// // 	console.log(i, 'Hello World');
// // }

// // const nums = [12, 34, 56, 34, 78, 54, 23, 12];

// // for (let i = 0; i < nums.length; i++) {
// // 	console.log(nums[i]);
// // }

// // const movies = [
// // 	{ movieName: 'Inception', rating: 3.8 },
// // 	{ movieName: 'Avengers', rating: 3.4 },
// // 	{ movieName: 'Iron Man', rating: 2.9 },
// // ];

// // for (let i = 0; i < movies.length; i++) {
// // 	let movie = movies[i];
// // 	console.log(`${movie.movieName} has a rating of ${movie.rating}`);
// // }

// const word = 'Hello World';

// // for (let i = 0; i < word.length; i++) {
// // 	console.log(word[i]);
// // }

// // let reversedWord = '';

// // for (let i = word.length - 1; i >= 0; i--) {
// // 	reversedWord = reversedWord + word[i];
// // }

// // console.log(reversedWord);

// // for (let i = 0; i < 5; i++) {
// // 	console.log('OUTER LOOP', i);

// // 	for (let j = 0; j < 5; j++) {
// // 		console.log('      INNER LOOP', j);
// // 	}
// // }

// const gameBoard = [
// 	[4, 64, 8, 4],
// 	[128, 32, 4, 16],
// 	[16, 4, 4, 32],
// 	[2, 16, 16, 2],
// ];
// let total = 0;
// for (let i = 0; i < gameBoard.length; i++) {
// 	// console.log(gameBoard[i]);

// 	for (let j = 0; j < gameBoard[i].length; j++) {
// 		// console.log(gameBoard[i][j]);
// 		total += gameBoard[i][j];
// 	}
// }

// console.log(total);

// // const gameBoard = [
// // 	[
// // 		[4, 64, 8, 4, 4, 5],
// // 		[4, 64, 8],
// // 		[4],
// // 		[4, 64, 8, 4, 12, 2, 3, 234, 54, 6456],
// // 	],
// // 	[`
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 	],
// // 	[
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 	],
// // 	[
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 		[4, 64, 8, 4],
// // 	],
// // ];

// for (let i = 0; i < 5; i++) {
// 	console.log(i);
// }

// let i = 0;
// while (i < 5) {
// 	console.log(i);
// 	i++;
// }

// const target = Math.floor(Math.random() * 10);
// let guess = Math.floor(Math.random() * 10);
// let count = 1;
// while (guess !== target) {
// 	console.log(`Target: ${target} | Guess: ${guess}`);
// 	guess = Math.floor(Math.random() * 10);
// 	count++;
// }

// console.log(count);
// console.log(`Target: ${target} | Guess: ${guess}`);

// const target = Math.floor(Math.random() * 10);
// let guess = Math.floor(Math.random() * 10);

// while (true) {
// 	console.log(`Target: ${target} | Guess: ${guess}`);
// 	if (guess === target) {
// 		break;
// 	}
// 	guess = Math.floor(Math.random() * 10);
// }

// console.log(`Target: ${target} | Guess: ${guess}`);

// for (let i = 0; i < 10; i++) {
// 	console.log(i);
// 	if (i === 5) {
// 		break;
// 	}
// }

// let categories = [
// 	'fashion',
// 	'electronics',
// 	'mobiles',
// 	'books',
// 	'toys',
// 	'groceries',
// ];

// for (let i = 0; i < categories.length; i++) {
// 	console.log(categories[i]);
// }

// for (let category of categories) {
// 	console.log(category);
// }

// for (let char of 'Hello World') {
// 	console.log(char);
// }

// const matrix = [
// 	[1, 4, 7],
// 	[9, 7, 2],
// 	[9, 4, 6],
// ];

// for (let row of matrix) {
// 	for (let num of row) {
// 		console.log(num);
// 	}
// }

// const cats = ['fashion', 'mobiles', 'books'];
// const prods = ['tshirt', 'samsung', '1984'];

// for (let i = 0; i < cats.length; i++) {
// 	console.log(cats[i], prods[i]);
// }

// const productPrices = {
// 	Apple: 80000,
// 	OnePlus: 50000,
// 	Samsung: 90000,
// };

// for (let key of Object.keys(productPrices)) {
// 	console.log(key, productPrices[key]);
// }

// for (let key in productPrices) {
// 	console.log(key, productPrices[key]);
// }

// for (let key of Object.keys(productPrices)) {
// 	console.log(key);
// }

// for (let value of Object.values(productPrices)) {
// 	console.log(value);
// }

const movieRating = {
	pursuitOfHappiness: 4.8,
	satya: 4.8,
	gangsOfWasepur: 4,
	robot: -3,
};

for (let movie in movieRating) {
	// console.log(movie)
	console.log(`${movie} has a rating of ${movieRating[movie]}`);
}

Scratchpad #6

// function greet() {
// 	console.log('Hello World');
// }

// greet();

// function rollDie() {
// 	let roll = Math.floor(Math.random() * 6) + 1;
// 	console.log(`Rolled: ${roll}`);
// }

// function throwDice() {
// 	rollDie();
// 	rollDie();
// 	rollDie();
// }

// throwDice();

// console.log('hello world');

// // person - parameter
// function greet(person) {
// 	console.log(`Hello ${person}`);
// }

// greet('John Doe'); // argument
// greet('Jane Doe'); // argument
// greet('Jill Smith'); // argument

// function greet(message, person) {
// 	console.log(`${message}, ${person}`);
// }

// greet('Hello', 'John');
// greet('Hi', 'John');
// greet('Hi');
// greet('hi', 'john', 'jane', 'jack');

// function rollDie() {
// 	let roll = Math.floor(Math.random() * 6) + 1;
// 	console.log(`Rolled: ${roll}`);
// }

// function throwDice(times) {
// 	for (let i = 0; i < times; i++) {
// 		rollDie();
// 	}
// }

// throwDice(2);

// let firstName = 'John';

// firstName.toUpperCase();

// function add(x, y) {
// 	return x + y;
// }

// console.log(add(10, 5));

// function isNumber(val) {
// 	if (typeof val === 'number') {
// 		return true;
// 	}
// 	return false;
// }

// isNumber('10');

// let firstName = 'Jane';

// function greet() {
// 	let firstName = 'John';
// 	console.log(firstName);
// }

// greet();
// console.log(firstName);

// let lastName = 'Doe';

// if (true) {
// 	var lastName = 'Smith';
// 	console.log(lastName);
// }

// console.log(lastName);

// for (var i = 0; i < 10; i++) {
// 	console.log(i);
// }

// console.log('OUTSIDE THE BLOCK', i);

// function outer() {
// 	let message = 'Hello World';

// 	function inner() {
// 		let message = 'Goodbye';
// 		console.log(message);
// 	}

// 	console.log(message);
// 	inner();
// }

// outer();

// // Named function
// function square(num) {
// 	return num ** 2;
// }

// console.log(square);

// const sq = square;
// const num = 'Hello';

// console.log(sq(10));

// console.log(square(10));

// // Named function
// function square(num) {
// 	return num ** 2;
// }

// const sq = function (num) {
// 	return num ** 2;
// };

// console.log(sq(100));

// function math(x, y, fn) {
// 	return fn(x, y);
// }

// function add(a, b) {
// 	return a + b;
// }

// function sub(a, b) {
// 	return a - b;
// }

// console.log(math(10, 5, sub));

// console.log(
// 	math(10, 5, function (a, b) {
// 		return a * b;
// 	})
// );

// const math = [
// 	function (a, b) {
// 		return a + b;
// 	},
// 	function (a, b) {
// 		return a - b;
// 	},
// 	function (a, b) {
// 		return a * b;
// 	},
// 	function (a, b) {
// 		return a / b;
// 	},
// ];

// console.log(math[0](10, 5));

// const math = {
// 	add: function (a, b) {
// 		return a + b;
// 	},
// 	sub: function (a, b) {
// 		return a - b;
// 	},
// 	mul: function (a, b) {
// 		return a * b;
// 	},
// 	div: function (a, b) {
// 		return a / b;
// 	},
// };

// console.log(math.add(10, 5));

function add(x, y) {
	return x + y;
}

const sub = function (x, y) {
	return x - y;
};

const mul = function (x, y) {
	return x * y;
};

function div(x, y) {
	return x / y;
}

const operations = [add, sub, mul, div];

console.log(operations[0]);
console.log(operations[0](10, 23));
console.log(operations[2](10, 4));

Scratchpad #7

var hello;

// // function math(a, b, fn) {
// // 	return fn(a, b);
// // }

// // console.log(
// // 	math(10, 20, function (a, b) {
// // 		return a + b;
// // 	})
// // );

// // // Example 2
// // function repeat(func, num) {
// // 	for (let i = 0; i < num; i++) {
// // 		func();
// // 	}
// // }

// // function sayHello() {
// // 	console.log('Hello World!');
// // }
// // function sayGoodbye() {
// // 	console.log('Bye World!');
// // }

// // repeat(sayHello, 10);
// // repeat(sayGoodbye, 5);

// // // Example 3
// // function randomPick(f1, f2) {
// // 	let randNum = Math.random();
// // 	if (randNum < 0.5) {
// // 		f1();
// // 	} else {
// // 		f2();
// // 	}
// // }

// // randomPick(sayHello, sayGoodbye);

// // function raiseBy(num) {
// // 	return function (x) {
// // 		return x ** num;
// // 	};
// // }

// // // const n = Math.random();
// // const square = raiseBy(2);
// // const cube = raiseBy(3);
// // const hypercube = raiseBy(4);

// // console.log(square(5));
// // console.log(cube(5));
// // console.log(hypercube(5));

// function isBetween(x, y) {
// 	return function (val) {
// 		return val >= x && val < y;
// 	};
// }

// const isUnderAge = isBetween(18, 21);
// const isLegalAge = isBetween(21, 65);

// console.log(isLegalAge(18));

// function isBetween(x, y) {
// 	return function (num) {
// 		return num >= x && num <= y;
// 	};
// }

// const isUnderAge = isBetween(0, 18);
// const canEnterButNotDrink = isBetween(18, 21);
// const canDrink = isBetween(21, 65);
// const isSenior = isBetween(65, 100);

// console.log(isUnderAge(5));
// console.log(canEnterButNotDrink(20));
// console.log(canDrink(30));
// console.log(isSenior(70));

// function math(a, b, fn) {
// 	return fn(a, b);
// }

// function add(a, b) {
// 	return a + b;
// }

// console.log(math(10, 5, add));
// console.log(
// 	math(10, 5, function (a, b) {
// 		return a - b;
// 	})
// );

// function hello() {
// 	console.log('Hello World');
// }

// // setTimeout(hello, 2000);
// setInterval(hello, 1000);

// hello();

// function hello() {
// 	console.log('Hello World');
// }

// let hello = 'Hello World';
// console.log(hello);

// const arr1 = [1, 2, 3, 4, 5];

// for (let num of arr1) {
// 	console.log();
// }

// for (let num of arr1) {
// 	console.log(num);
// }

// arr1.forEach(function (num) {
// 	if (num % 2 === 0) {
// 		console.log(num);
// 	}
// });

// const movies = [
// 	{
// 		title: 'Avengers',
// 		rating: 4.1,
// 	},
// 	{
// 		title: 'Dr. Strange',
// 		rating: 3.9,
// 	},
// 	{
// 		title: 'Tenet',
// 		rating: 4.3,
// 	},
// 	{
// 		title: 'Joker',
// 		rating: 4.7,
// 	},
// ];

// movies.forEach(function (movie, i) {
// 	console.log(i, movie.title);
// });

// const names = ['john', 'jack', 'jane', 'james'];

// const upperNames = names.map(function (name) {
// 	return name.toUpperCase();
// });

// console.log(upperNames);

// const upper_names = [];

// for (let name of names) {
// 	upper_names.push(name.toUpperCase());
// }

// console.log(upper_names);

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// const doubles = nums.map(function (num) {
// 	return num * 2;
// });

// const numDetails = nums.map(function (num) {
// 	return {
// 		number: num,
// 		isEven: num % 2 === 0,
// 	};
// });

// console.log(numDetails);

// function square(x) {
// 	return x * x
// }

// const square = function (x) {
// 	return x * x;
// }

// const square = (x) => {
// 	return x * x;
// }

// const square = x => {
// 	return x * x;
// }

// const square = x => (
// 	x * x
// )

// const square = x => (x * x);

// const square = x => x * x;

// console.log(square(10));

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// // const doubles = nums.map(function (num) {
// // 	return num * 2;
// // });

// const doubles = nums.map(num => num * 2);

// let movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];

// const result = movies.find(function (movie) {
// 	return movie[0] === 'J';
// });

// console.log(result);

// const result = movies.find((movie) => {
// 	return movie.includes('Hello');
// });

// console.log(result);

// const books = [
// 	{
// 		title: 'The Shining',
// 		author: 'Stephen King',
// 		rating: 4.1,
// 	},
// 	{
// 		title: 'Sacred Games',
// 		author: 'Vikram Chandra',
// 		rating: 4.5,
// 	},
// 	{
// 		title: '1984',
// 		author: 'George Orwell',
// 		rating: 4.9,
// 	},
// 	{
// 		title: 'The Alchemist',
// 		author: 'Paulo Coelho',
// 		rating: 3.5,
// 	},
// 	{
// 		title: 'The Great Gatsby',
// 		author: 'F. Scott Fitzgerald',
// 		rating: 3.8,
// 	},
// ];

// // const result = books.find((book) => book.rating < 4);
// // const result = books.find((book) => book.author.includes('George'));
// const result = books.filter((book) => book.rating < 4);

// console.log(result);

// const goodBook = books.filter(b => b.rating >= 4.3)

// const georgeBooks = books.filter(b => (
//   b.author.includes('George')
// ))

// const lowRated = books.filter(book => {
//   return book.rating < 4
// })

// let query = 'the'
// const filteredBooks = books.filter(book => {
//   const title = book.title.toLowerCase()
//   return title.includes(query)
// })

// console.log(goodBook)
// console.log(georgeBooks)
// console.log(lowRated)
// console.log(booksWithThe)

const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];

const result = names.some((name) => name[0] === 'j');
console.log(result);

Scratchpad #8

// const prices = [500.4, 211, 23, 5, 4, 22.2, -23.2, 9233];
// // prices.sort((a, b) => a - b);
// prices.sort((a, b) => b - a);
// console.log(prices);

// const arr1 = [1, 2, 3, 4, 5];

// // acc  currVal
// // 1    2
// // 3    3
// // 6    4
// // 10   5
// // 15

// // const result = arr1.reduce((acc, currVal) => {
// // 	return acc + currVal;
// // });
// const result = arr1.reduce((acc, currVal) => {
// 	return acc * currVal;
// });

// console.log(result);

// let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];

// // acc  currVal
// // 21		221
// // 221	2
// // 221  1
// // 221  34
// // 221  123
// // 221  4342
// // 4342  ...

// const maxVal = nums.reduce((acc, currVal) => {
// 	if (currVal > acc) {
// 		return currVal;
// 	}
// 	return acc;
// });
// console.log(maxVal);

// // A shorter way is to use the Math.max and implicit return
// const maxVal = nums.reduce((max, currVal) => Math.max(max, currVal))
// console.log(maxVal)

// const arr1 = [1, 2, 3, 4, 5];

// const result = arr1.reduce((acc, currVal) => {
// 	return acc + currVal;
// }, 100);

// console.log(result);

// function multiply(a, b) {
// 	if (typeof b === 'undefined') {
// 		b = 1;
// 	}
// 	return a * b;
// }

// function multiply(a = 1, b = 1) {
// 	return a * b;
// }

// console.log(multiply(10));

// const nums = [10, 2, 45, 7];

// console.log(Math.max(...nums));

// function printVals(a, b, c) {
// 	console.log(a);
// 	console.log(b);
// 	console.log(c);
// }

// const names = ['john', 'jack', 'jane', 'jill'];

// // printVals(...names);
// printVals(...'John');

// function add(...nums) {
// 	let total = 0;
// 	for (let num of nums) {
// 		total += num;
// 	}
// 	return total;
// }

// console.log(add(10, 5, 12));

// function printNames(name1, name2, ...others) {
// 	console.log(name1);
// 	console.log(name2);
// 	console.log(others);
// }

// printNames('John', 'Jane', 'jack', 'jill', 'james');

// const users = ['john', 'jane', 'jack'];

// // const admin = users[0];
// // const mod = users[1];
// // const user = users[2];

// const [admin, ...others] = users;

// console.log(admin, others);

// const user = {
// 	firstName: 'John',
// 	lastName: 'Doe',
// 	email: 'john.doe@gmail.com',
// 	phone: 99982234567,
// };

// // const firstName = user.firstName;
// // const lastName = user.lastName;

// // const { firstName, lastName, email: emailAddress, phone } = user;
// const { firstName, lastName, ...others } = user;

// console.log(firstName, lastName, others);

// function profile({ firstName, lastName, profession }) {
// 	console.log(`My name is ${firstName} ${lastName} and I am a ${profession}`);
// }

// profile({ firstName: 'John', lastName: 'Doe', profession: 'Dev' });

// const movieReviews = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];
// const highest = Math.max(...movieReviews);
// const lowest = Math.min(...movieReviews);

// let total = 0;
// movieReviews.forEach((rating) => (total += rating));
// const average = total / movieReviews.length;

// const info = {
// 	highest,
// 	lowest,
// 	average,
// };
// console.log(info);

// const getReviewDetails = (arr) => {
// 	const highest = Math.max(...arr);
// 	const lowest = Math.min(...arr);
// 	const total = arr.reduce((accumulator, nextVal) => accumulator + nextVal);
// 	const average = total / arr.length;

// 	return {
// 		highest,
// 		lowest,
// 		total,
// 		average,
// 	};
// };

// const reviewList = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];

// const statistics = getReviewDetails(reviewList);
// console.log(statistics);

// const username = 'janedoe';
// const role = 'admin';

// // const user1 = { [role]: username };
// const user1 = { [1 + 2 + 3 + 4]: username };
// console.log(user1);

// const addProperty = (obj, k, v) => {
// 	return { ...obj, [k]: v };
// };

// console.log(addProperty({ firstName: 'john' }, 'lastName', 'Doe'));

const math = {
	multiply(x, y) {
		return x * y;
	},
	divide(x, y) {
		return x / y;
	},
	square(x) {
		return x * x;
	},
	PI: 3.14,
};

console.log(math.square(5));

Scratchpad #9

// // // // Global Scope {}
// // // // let firstName = 'John';

// // // let firstName = 'John';

// // // function namaste() {
// // // 	// Local Scope
// // // 	// console.log(firstName);
// // // 	console.log(this);
// // // }

// // // namaste();

// // // // const profile = {
// // // // 	firstName: 'John',
// // // // 	lastName: 'Doe',
// // // // 	age: 20,
// // // // 	greet() {
// // // // 		console.log(this);
// // // // 	},
// // // // };

// // // // namaste();
// // // // profile.greet();

// // function greet() {
// // 	console.log(
// // 		`Hello, my name is ${this.firstName} ${this.lastName} and I am ${this.age} years old.`
// // 	);
// // }

// // // greet();

// // const john = {
// // 	firstName: 'John',
// // 	lastName: 'Doe',
// // 	age: 22,
// // 	greet,
// // };

// // const jane = {
// // 	firstName: 'Jane',
// // 	lastName: 'Smith',
// // 	age: 20,
// // 	greet,
// // };

// // jane.greet();

// // // const user = {
// // // 	firstName: 'Jane',
// // // 	lastName: 'Doe',
// // // 	age: 20,
// // // };

// // // user.greet();

// // const user = {
// // 	firstName: 'John',
// // 	lastName: 'Doe',
// // 	role: 'admin',
// // 	fullName() {
// // 		return `${this.firstName} ${this.lastName} is an ${this.role}`;
// // 	},
// // 	logDetails() {
// // 		console.log(`${this.fullName()} and is cool!`);
// // 	},
// // };

// // user.logDetails();

// // const log = user.logDetails;

// // log();

// const hellos = {
// 	messages: [
// 		'hello world',
// 		'hello universe',
// 		'hello darkness',
// 		'hello hello',
// 		'heylo',
// 	],
// 	pickMsg() {
// 		const index = Math.floor(Math.random() * this.messages.length);
// 		return this.messages[index];
// 	},
// 	start() {
// 		setInterval(() => {
// 			// this = window
// 			console.log(this.pickMsg());
// 		}, 1000);
// 	},
// };

// // hellos.start();

// console.dir(document);

// const para = document.getElementById('special');
// console.dir(para);

// const lis = document.getElementsByTagName('li');
// console.log(lis);

// const ps = document.getElementsByClassName('red-text');
// console.log(ps);

// const lst = document.getElementsByClassName('my-list');
// // console.log(lst[0]);

// const lis = lst[0].getElementsByTagName('li');
// console.log(lis);

// const spc = document.querySelectorAll('li');
// console.log(spc);

// const h1 = document.querySelector('h1');
// // console.log(h1.innerText);

// h1.innerText = 'THIS HAS CHANGED!';

// const para = document.querySelector('.special');
// console.log(para.textContent);

// const para = document.querySelector('.red-text');
// para.innerHTML = 'Hello <b>World</b>';
// para.innerHTML += '<i> This is some more text</i>';

const inp = document.querySelector('input');
const a = document.querySelector('a');

inp.id = 'helloworld';
inp.value = 'Hello World';
a.href = 'https://yahoo.com';
// console.log(inp.id);
// console.log(a.href);

Scratchpad #10

// const link = document.querySelector('a');
// console.log(link.href);
// console.log(link.getAttribute('href'));
// link.href = 'https://yahoo.com';
// link.setAttribute('href', 'https://yahoo.com');

// const ul = document.querySelector('ul');
// const li = ul.querySelector('li');
// // console.log(li.parentElement.parentElement);
// // console.log(ul.children);
// // console.log(li.nextElementSibling.nextElementSibling.innerText);
// console.log(li.previousElementSibling);

// const lis = document.querySelectorAll('li');
// for (let li of lis) {
// 	li.innerText = 'CHANGED!';
// }

// const h1 = document.querySelector('h1');
// h1.style.color = 'red';
// h1.style.backgroundColor = 'yellow';
// h1.style.padding = '20px 40px';

// const lis = document.querySelectorAll('li');
// const colors = ['red', 'yellow', 'green', 'orange', 'teal'];

// for (let li of lis) {
// 	li.style.color = colors[Math.floor(Math.random() * colors.length)];
// 	li.style.fontSize = '20px';
// 	li.style.fontWeight = 'bold';
// 	li.style.backgroundColor = 'black';
// }

// const h1 = document.querySelector('h1');
// const h1Styles = getComputedStyle(h1);
// console.log(h1Styles.backgroundColor);

// const t1 = document.querySelector('.todo');
// console.log(t1.innerText);

// t1.setAttribute('class', 'todo done');
// t1.classList.add('done');
// t1.classList.remove('todo');
// t1.classList.toggle('todo');
// console.log(t1.classList);

// const root = document.querySelector('#root');

// const h2 = document.createElement('h2');
// h2.innerText = 'I was created using JavaScript';
// h2.style.fontFamily = 'Arial';
// h2.style.color = 'blue';

// const section = document.createElement('section');
// section.style.padding = '20px 40px';
// section.style.border = '4px dashed black';
// section.appendChild(h2);

// root.appendChild(section);

// const list = document.querySelector('.my-list');
// const newTask = document.createElement('li');
// newTask.innerText = 'One more task';

// const task1 = document.querySelector('.my-list li');

// // console.log(task1.innerText);
// // list.appendChild(newTask);

// list.insertBefore(newTask, task1);

// const p = document.querySelector('.red-text');

// const b = document.createElement('b');
// b.innerText = 'Hello World';
// const i = document.createElement('i');
// i.innerText = 'Hello Universe';

// // p.insertAdjacentElement('afterend', b);

// p.prepend(b, i);

// // const list = document.querySelector('.my-list');
// const task1 = document.querySelector('.my-list li');
// // console.log(task1);

// // list.removeChild(task1);
// task1.remove();

// const btn = document.querySelector('button');
// console.log(btn);
// btn.onclick = function () {
// 	console.log('Hello World');
// };
// btn.onclick = function () {
// 	console.log('Hello Universe');
// };

// btn.addEventListener('click', function () {
// 	console.log(Math.random());
// });
// btn.addEventListener('click', function () {
// 	console.log('hello world');
// });
// btn.addEventListener('mouseenter', function () {
// 	document.body.style.backgroundColor = 'yellow';
// });
// btn.addEventListener('mouseout', function () {
// 	document.body.style.backgroundColor = 'white';
// });

// window.addEventListener('scroll', function () {
// 	console.log(Math.random());
// });

// const btn = document.querySelector('button');
// btn.style.position = 'relative';

// btn.addEventListener('mouseover', function () {
// 	const height = Math.floor(Math.random() * window.innerHeight);
// 	const width = Math.floor(Math.random() * window.innerWidth);
// 	btn.style.left = `${width}px`;
// 	btn.style.top = `${height}px`;
// });

// btn.addEventListener('click', function () {
// 	document.body.style.backgroundColor = 'green';
// 	btn.innerText = 'You won!';
// });

// const colors = [
// 	'red',
// 	'orange',
// 	'yellow',
// 	'green',
// 	'blue',
// 	'purple',
// 	'indigo',
// 	'violet',
// ];

// const container = document.querySelector('#boxes');

// for (let color of colors) {
// 	const box = document.createElement('div'); // Create a square box
// 	box.style.backgroundColor = color; // Style the box
// 	box.classList.add('box'); // Add a class
// 	container.append(box); // Append box to container
// 	box.addEventListener('click', function () {
// 		console.log(box.style.backgroundColor);
// 	});
// }

// const inp = document.querySelector('input');
// const button = document.querySelector('button');
// const allTasks = document.querySelector('#allTasks');

// button.addEventListener('click', function (event) {
// 	console.dir(event.target);
// 	// div
// 	//		checkbox -> click
// 	// 		span
// 	// 		button -> delete
// 	const li = document.createElement('li');
// 	li.innerText = inp.value;
// 	const del = document.createElement('button');
// 	del.innerText = 'Delete';
// 	li.append(del);
// 	allTasks.append(li);

// 	li.addEventListener('click', function () {
// 		li.remove();
// 	});

// 	inp.value = '';
// });

const inp = document.querySelector('input');
// const p = document.querySelector('p');
const allTasks = document.querySelector('#allTasks');

inp.addEventListener('keypress', function (event) {
	// p.innerText = event.target.value;
	if (event.key === 'Enter') {
		const li = document.createElement('li');
		li.innerText = event.target.value;
		allTasks.append(li);
		inp.value = '';
	}
});

Scratchpad #11

// function multiply(x, y) {
// 	return x * y;
// }

// function square(x) {
// 	return multiply(x, x);
// }

// function rightTriangle(a, b, c) {
// 	return square(a) + square(b) === square(c);
// }

// rightTriangle(1, 2, 3);

// console.log('The first log');
// alert('Hello World');
// console.log('The second log');

// console.log('The first log');
// setTimeout(function () {
// 	console.log('Long process completed. Here is your output ----> OUTPUT');
// }, 3000);
// console.log('The second log');

// const btn = document.querySelector('button');

// setTimeout(function () {
// 	btn.style.transform = 'translateX(100px)';
// 	setTimeout(function () {
// 		btn.style.transform = 'translateX(200px)';
// 		setTimeout(function () {
// 			btn.style.transform = 'translateX(300px)';
// 			setTimeout(function () {
// 				btn.style.transform = 'translateX(400px)';
// 				setTimeout(function () {
// 					btn.style.transform = 'translateX(500px)';
// 				}, 1000);
// 			}, 1000);
// 		}, 1000);
// 	}, 1000);
// }, 1000);

// const willGetAPlaystation = new Promise((resolve, reject) => {
// 	const random = Math.random();

// 	if (random < 0.5) {
// 		reject();
// 	} else {
// 		resolve();
// 	}
// });

// willGetAPlaystation
// 	.then(() => {
// 		console.log('Thanks for the playstation.');
// 	})
// 	.catch(() => {
// 		console.log('&*%^%*&^%');
// 	});

const makePlayStationPromise = () => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			const random = Math.random();
			if (random < 0.5) {
				reject();
			} else {
				resolve();
			}
		}, 2000);
	});
};

makePlayStationPromise()
	.then(() => {
		console.log('Thanks for the playstation.');
	})
	.catch(() => {
		console.log('&*%^%*&^%');
	});

Project

  1. Generate some boilerplate for a basic React application.
    • Go into your workspace/projects directory using the terminal.
    • cd ~/Documents/FullStack/Workspace
    • mkdir rststore
    • npx create-react-app@latest frontend –use-npm
    • code .
    • cd frontend
    • npm start
    • Open public/index.html and clean up the file. Remove all the comments and change the title and meta content.
    • Delete all the files in the src folder. Create and add basic boilerplate code to App.js and index.js.

2. Chakra UI Installation and Setup

  • npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
  • npm install react-icons –save
  • Edit index.js file. Import ChakraProvider component and wrap the App component with it.

3. Create Header and Footer components

  • Create a folder called src/components in the src folder and add all components in that.

4. Create HomeScreen product listings

  • Create the HomeScreen component (all display/screen components will go in the /screens folder), along with the product and ratings components.

5. Install and Implement React Router

  • npm install react-router-dom
  • Complete all the React Router setup on the App page.
  • Modify Product cards, Header links etc. Use React Routers Link component instead.

6. Design and build the ProductScreen component.

  1. Setting up the backend
    • Close the React server.
    • Create a folder named backend outside the frontend folder in the root of our project.
    • npm init in the root. (not inside the backend or frontend folders, but outside in the root directory)
    • During npm init setup the main will be server.js
    • npm install express (in the root folder)
    • Create a file backend/server.js in the backend folder and a folder data and copy products.js to this folder.
    • Create some routes to serve the data from the backend
    • Create a script for start in package.json
    • Create 2 basic routes for ‘/’ and ‘/api/products’
    • Convert products.js export statement to commonjs format.
    • Create another route to fetch single product by id.
  1. Fetching data from our backend using React
    • Inside the frontend folder, run npm install axios
    • Modify the HomeScreen component to fetch and store data in the component.
    • To fix the issue of our backend address for now, we’ll add a proxy to the frontend’s package.json. Add this “proxy”: “http://127.0.0.1:5000”, to frontend/package.json
    • Make sure both frontend and backend are running in two terminals and test it out.
    • Modify the ProductScreen component to also make a request to our backend to fetch data.
    • Delete the projects.js file from our frontend’s src folder as we no longer need it.

9. More backend setup

  • In the root directory: run
  • npm install -D nodemon concurrently. ‘-D’ is a dev dependency, meaning we only need these modules during development.
  • These above packages will help us auto restart our server when we change our code, so we don’t have to do it manually.
  • Modify scripts in package.json (root folder) to add some scripts to use our npm command directly to work them.

10. Setup environment variables

  • npm install dotenv
  • Do the dotenv setup in server.js file and create a .env file in the root folder.

11. Convert imports to ES Modules

  • Add “type”: “module” to package.json file. Change all import and export statements to ES module style.
  • Note: You will have to add .js extension while using ES modules in the backend.

12. Install and setup MongoDB

  • After installation, setup MongoDB Compass
  • Use this as the connection string: mongodb://localhost:27017/rststore
  • Add the following in the .env
    MONGO_URI = mongodb://localhost:27017/rststore

13. Connect to the database

  • Install mongoose: npm install mongoose (in the root folder)
  • Create a folder named config in the backend folder and create a file named backend/config/db.js inside it.
  • Do all the mongoDB connection setup
  • Import db.js into server.js and run the connectDB function.
  • Start the server and check if any error.

14. Improve console log messages.

  • Run this command in the root folder: npm install colors
  • Add stylings to server and db console messages.

15. Create database models for data

  • Create a models folder inside the backend folder.
  • Create all our data model schemas.

16. Prepare sample data for the backend data seeding

  • Delete all the _id key-values from the products.js as MongoDB
    will automatically create it for us.
  • Create data/users.js file and fill it with a few user objects.
  • npm install bcryptjs – for password hashing
  • Use bcryptjs for the password fields to encrypt the password. (temporary)

17. Create database seeder for quick sample data generation (optional)

  • Create backend/seeder.js file inside the backend folder.
  • Add seeding logic and create import and destroy scripts.

18. Fetching products from the database

  • Create a folder named backend/routes in the backend folder.
  • Create a file named backend/routes/productRoutes.js
  • npm install express-async-handler – we will wrap our callbacks with this function so that we can do error handler in a better way.
  • Move the products and single product fetch routes to this file and add all the logic for now.
  • Test the routes in Postman

19. Do Postman setup to work with our API (optional)Custom error handling. Run the following in the root folder.

20. Custom error handling. Run the following in the root folder.

  • npm install express-async-handler
  • Create a folder named backend/middleware in the backend folder
  • Create an errorMiddleware.js and add logic to handle errors.

21. Introduction to Redux

  • The Redux Pattern
  • Download the Redux DevTools brower extension.
  • Go to the frontend folder. cd frontend
  • npm install redux react-redux redux-thunk redux-devtools-extension
  • In the src folder, create a file named store.js
  • Import Provider and store into the index.js and do all the setup.

22. Create our first reducer

  • In frontend/src create a folder called reducers – (frontend/src/reducers).
  • Create a file (our reducer) named productReducer.js inside the reducers folder and add all the reducer logic.
  • Next, import productListReducer to store.js and add it to the combineReducers({}) function’s argument object as a new key/value.
  • Create a folder called constants in the frontend/src folder and inside it create the productConstants.js file to store all our action names.
  • Create a folder called actions in the frontend/src folder and inside it create the productActions.js file to store all our action functions. We will dispatch actions to our reducer.
  • All these steps, we do for each resource of our app. So, whether it’s products, or users or some other model/feature, this is the format/pattern we will follow for Redux. We create the constant, the reducer the action and then we fire it off in the component.
  • Next, we now want to fire this action off in our HomeScreen components where we need this products data.

  1. Getting Redux State in the Home Screen
    • Clean up the file. Remove axios import, the [products, setProducts] state variables and remove everything from inside useEffect. We don’t need these anymore.
    • Import useDispatch and useSelector from ‘react-redux’. Also import listProducts from ‘../actions/productActions’.
    • The first hook will be used to dispatch/call an action, and the other is use to select parts of the state. Here we will need the productList part of the state.
    • Create the dispatch object using the useDispatch hook and call it in useEffect to fire the listProducts action.
    • To select products from our state, we need to use the useSelector hook. This hook will take in an arrow function. This function gets state and then we can select which part of the state do we want.
    • Add a conditional to display a loading messageerror message or our product list.

24. Create Message and Loader components.

  • Use the Spinner and Alert components from ChakraUI to add these.

25. Single product details screen Reducer and Action

  • Again, we will follow the same pattern/steps as earlier.
  • Start off by adding the required constants. Since this is for the single product screen, we will add the constants once again to the productConstants.js
  • Create a new reducer named productDetailsReducer in productReducers.js.
  • Whenever we create a new reducer, we have to add it to our store. So, import productDetailsReducer in the store.js file and add a new piece of state named productDetails.
  • Next, step will be to create an action. Add a new action named listProductDetails to the actions file.
  • Next, in the ProductScreen.js, get rid of axios and clean up useEffect. Import useDispatchuseSelector and the listProductDetails action that we just created.
  • Create the dispatch object and dispatch the listProductDetails action in the useEffect hook. You will now be able to see the state in Redux Devtools.
  • Use useSelector hook and select the productDetails piece of state. De-structure the correct values and use them in the JSX to display the product details, error and loading components.

26. Cart and Quantity

  • Add a quantity select box with it’s logic to only contain the number of items in stock.
  • The add to cart button should redirect to the a cart page/screen with the product id and quantity as a query string.

27. Cart Screen and Route

  • Create screens/CartScreen.js file in the screens folder.
  • Import this new CartScreen.js component in the App.js file and create a route for the Cart screen<Route path=’/cart/:id?’ component={CartScreen} />
  • The :id? question mark here means that this id is optional in the route/address. Because if we directly go to the cart page we will not have any id.

Project

  1. Generate some boilerplate for a basic React application.
    • Go into your workspace/projects directory using the terminal.
    • cd ~/Documents/FullStack/Workspace
    • mkdir rststore
    • npx create-react-app@latest frontend –use-npm
    • code .
    • cd frontend
    • npm start
    • Open public/index.html and clean up the file. Remove all the comments and change the title and meta content.
    • Delete all the files in the src folder. Create and add basic boilerplate code to App.js and index.js.

2. Chakra UI Installation and Setup

  • npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
  • npm install react-icons –save
  • Edit index.js file. Import ChakraProvider component and wrap the App component with it.

Project

  1. Generate some boilerplate for a basic React application.
    • Go into your workspace/projects directory using the terminal.
    • cd ~/Documents/FullStack/Workspace
    • mkdir rststore
    • npx create-react-app@latest frontend –use-npm
    • code .
    • cd frontend
    • npm start
    • Open public/index.html and clean up the file. Remove all the comments and change the title and meta content.
    • Delete all the files in the src folder. Create and add basic boilerplate code to App.js and index.js.

2. Chakra UI Installation and Setup

  • npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
  • npm install react-icons –save
  • Edit index.js file. Import ChakraProvider component and wrap the App component with it.

3. Create Header and Footer components

  • Create a folder called src/components in the src folder and add all components in that.

4. Create HomeScreen product listings

  • Create the HomeScreen component (all display/screen components will go in the /screens folder), along with the product and ratings components.

5. Install and Implement React Router

  • npm install react-router-dom
  • Complete all the React Router setup on the App page.
  • Modify Product cards, Header links etc. Use React Routers Link component instead.

6. Design and build the ProductScreen component.

  1. Setting up the backend
    • Close the React server.
    • Create a folder named backend outside the frontend folder in the root of our project.
    • npm init in the root. (not inside the backend or frontend folders, but outside in the root directory)
    • During npm init setup the main will be server.js
    • npm install express (in the root folder)
    • Create a file backend/server.js in the backend folder and a folder data and copy products.js to this folder.
    • Create some routes to serve the data from the backend
    • Create a script for start in package.json
    • Create 2 basic routes for ‘/’ and ‘/api/products’
    • Convert products.js export statement to commonjs format.
    • Create another route to fetch single product by id.
  1. Fetching data from our backend using React
    • Inside the frontend folder, run npm install axios
    • Modify the HomeScreen component to fetch and store data in the component.
    • To fix the issue of our backend address for now, we’ll add a proxy to the frontend’s package.json. Add this “proxy”: “http://127.0.0.1:5000”, to frontend/package.json
    • Make sure both frontend and backend are running in two terminals and test it out.
    • Modify the ProductScreen component to also make a request to our backend to fetch data.
    • Delete the projects.js file from our frontend’s src folder as we no longer need it.

9. More backend setup

  • In the root directory: run
  • npm install -D nodemon concurrently. ‘-D’ is a dev dependency, meaning we only need these modules during development.
  • These above packages will help us auto restart our server when we change our code, so we don’t have to do it manually.
  • Modify scripts in package.json (root folder) to add some scripts to use our npm command directly to work them.

10. Setup environment variables

  • npm install dotenv
  • Do the dotenv setup in server.js file and create a .env file in the root folder.

11. Convert imports to ES Modules

  • Add “type”: “module” to package.json file. Change all import and export statements to ES module style.
  • Note: You will have to add .js extension while using ES modules in the backend.

12. Install and setup MongoDB

  • After installation, setup MongoDB Compass
  • Use this as the connection string: mongodb://localhost:27017/rststore
  • Add the following in the .env
    MONGO_URI = mongodb://localhost:27017/rststore

13. Connect to the database

  • Install mongoose: npm install mongoose (in the root folder)
  • Create a folder named config in the backend folder and create a file named backend/config/db.js inside it.
  • Do all the mongoDB connection setup
  • Import db.js into server.js and run the connectDB function.
  • Start the server and check if any error.

14. Improve console log messages.

  • Run this command in the root folder: npm install colors
  • Add stylings to server and db console messages.

15. Create database models for data

  • Create a models folder inside the backend folder.
  • Create all our data model schemas.

16. Prepare sample data for the backend data seeding

  • Delete all the _id key-values from the products.js as MongoDB
    will automatically create it for us.
  • Create data/users.js file and fill it with a few user objects.
  • npm install bcryptjs – for password hashing
  • Use bcryptjs for the password fields to encrypt the password. (temporary)

17. Create database seeder for quick sample data generation (optional)

  • Create backend/seeder.js file inside the backend folder.
  • Add seeding logic and create import and destroy scripts.

18. Fetching products from the database

  • Create a folder named backend/routes in the backend folder.
  • Create a file named backend/routes/productRoutes.js
  • npm install express-async-handler – we will wrap our callbacks with this function so that we can do error handler in a better way.
  • Move the products and single product fetch routes to this file and add all the logic for now.
  • Test the routes in Postman

19. Do Postman setup to work with our API (optional)Custom error handling. Run the following in the root folder.

20. Custom error handling. Run the following in the root folder.

  • npm install express-async-handler
  • Create a folder named backend/middleware in the backend folder
  • Create an errorMiddleware.js and add logic to handle errors.

21. Introduction to Redux

  • The Redux Pattern
  • Download the Redux DevTools brower extension.
  • Go to the frontend folder. cd frontend
  • npm install redux react-redux redux-thunk redux-devtools-extension
  • In the src folder, create a file named store.js
  • Import Provider and store into the index.js and do all the setup.

22. Create our first reducer

  • In frontend/src create a folder called reducers – (frontend/src/reducers).
  • Create a file (our reducer) named productReducer.js inside the reducers folder and add all the reducer logic.
  • Next, import productListReducer to store.js and add it to the combineReducers({}) function’s argument object as a new key/value.
  • Create a folder called constants in the frontend/src folder and inside it create the productConstants.js file to store all our action names.
  • Create a folder called actions in the frontend/src folder and inside it create the productActions.js file to store all our action functions. We will dispatch actions to our reducer.
  • All these steps, we do for each resource of our app. So, whether it’s products, or users or some other model/feature, this is the format/pattern we will follow for Redux. We create the constant, the reducer the action and then we fire it off in the component.
  • Next, we now want to fire this action off in our HomeScreen components where we need this products data.

  1. Getting Redux State in the Home Screen
    • Clean up the file. Remove axios import, the [products, setProducts] state variables and remove everything from inside useEffect. We don’t need these anymore.
    • Import useDispatch and useSelector from ‘react-redux’. Also import listProducts from ‘../actions/productActions’.
    • The first hook will be used to dispatch/call an action, and the other is use to select parts of the state. Here we will need the productList part of the state.
    • Create the dispatch object using the useDispatch hook and call it in useEffect to fire the listProducts action.
    • To select products from our state, we need to use the useSelector hook. This hook will take in an arrow function. This function gets state and then we can select which part of the state do we want.
    • Add a conditional to display a loading messageerror message or our product list.

24. Create Message and Loader components.

  • Use the Spinner and Alert components from ChakraUI to add these.

25. Single product details screen Reducer and Action

  • Again, we will follow the same pattern/steps as earlier.
  • Start off by adding the required constants. Since this is for the single product screen, we will add the constants once again to the productConstants.js
  • Create a new reducer named productDetailsReducer in productReducers.js.
  • Whenever we create a new reducer, we have to add it to our store. So, import productDetailsReducer in the store.js file and add a new piece of state named productDetails.
  • Next, step will be to create an action. Add a new action named listProductDetails to the actions file.
  • Next, in the ProductScreen.js, get rid of axios and clean up useEffect. Import useDispatchuseSelector and the listProductDetails action that we just created.
  • Create the dispatch object and dispatch the listProductDetails action in the useEffect hook. You will now be able to see the state in Redux Devtools.
  • Use useSelector hook and select the productDetails piece of state. De-structure the correct values and use them in the JSX to display the product details, error and loading components.

26. Cart and Quantity

  • Add a quantity select box with it’s logic to only contain the number of items in stock.
  • The add to cart button should redirect to the a cart page/screen with the product id and quantity as a query string.

27. Cart Screen and Route

  • Create screens/CartScreen.js file in the screens folder.
  • Import this new CartScreen.js component in the App.js file and create a route for the Cart screen<Route path=’/cart/:id?’ component={CartScreen} />
  • The :id? question mark here means that this id is optional in the route/address. Because if we directly go to the cart page we will not have any id.

28. Cart Functionality

  • Create constants/cartConstants.js and add CART_ADD_ITEM and CART_REMOVE_ITEM constant varaibles to it.
  • Create reducers/cartReducer.js and add the reducer logic.
  • Import cartReducer.js in store.js and add the cartReducer function to the combineReducers argument object.
  • Create actions/cartActions.js. Do the below steps for the building the cart actions.
  • Import axios. We need axios to make a request to /api/products/:id to get the data/fields for that particular product.
  • Import CART_ADD_ITEM from actions/cartActions.js.
  • Then create the addToCart function which will get a (id, qty). We will get both these from the URL params.
  • We will need to use thunk as we are making an async request. So we will return an async function from it. This async function will get (dispatch, getState)dispatch is used for dispatching as usual, but getState will allow us to get our entire state tree. So anything we want like productListproductDetailscart, we can get it using getState.
  • After dispatching, we also want to store this in localStorage.
  • getState().cart.cartItems will give us back a JavaScript object and we can only store strings in the browser localStorage. Hence we have to stringify it. And when we want to take it out and read, we will have to parse it using JSON.parse
  • So we saved it to localStorage but where do we get it to actually fill the state, whenever we reload. We do that in the store.js.
  • We will first see if there is anything in cartItems in the localStorage. If it’s there, then we will add it to the initial state, so always loaded on the app’s first load. If nothing is present in the localStorage then we will just add an empty array.

29. Completing CartScreen.js and creating ‘add to cart’ functionality

  • Build the add to cart functionality.
  • Finish the CartScreen.js component.
  • Add functionality to the Remove Item from cart button. Follow the steps below:
  • Add CART_REMOVE_ITEM to the cartReducer.js file.
  • Create an action named removeFromCart in the cartActions.js file.
  • Fire this action in the removeFromCartHandler function in the CartScreen component.

30. Clean up the backend routes by extracting their logic into controllers

  • In the backend folder, create a folder called controller and create a file called productController.js inside it.
  • Extract all the logic to the productController.js from the routes file. The routes file should now only be for routing and all logic will go in to the controllers.
  • In productRoutes.js instead of using the method router.use(), instead use router.route() and add the route inside and then chain the appropriate methods get, post, put, delete etc. to it. This way we can define different controller logic to the same route. We will see this in sometime.

31. User Authentication Endpoints (Backend Routes)

  • Create routes/userRoutes.js and controllers/userController.js.
  • Start by working on an auth route. So here we want to authenticate a user by email and password. And then we want to send back some data, a token which we can save on the client (browser), so in the frontend (browser) we can use that token to access protected pages/routes (react frontend routes).
  • Import the ../models/userModel.js as we will need it to create new users in the MongoDB database.
  • Create authUser controller function. Inside it, first thing is to get data from the body. This data is on the request object and is something that will be sent here (to the backend) by a POST request and is usually sent via a form on the frontend pages. We can also mimic this sending data using Postman.
  • Before getting the data, make a new folder in rststore Postman collection.. Add a folder called Users & Auth. Inside that create a new request. Name it POST /api/users/login with the url to {{URL}}/api/users/login and add an email & password object to Body of type JSON.
  • Now this object that we add to the body tab in Postman, what will be sent in an object (key-value) on the request object. We extract that from request.body.
  • But in order for parsing this JSON data that we get on the request object from the frontend/Postman, we need to add another middleware in server.js.
  • Add the following line after const app = express part. app.use(express.json())
  • Create the authUser controller function. Also import this into userRoutes.js and add a login route.
  • Also import userRoutes in server.js and add the routes for users..
  • app.use(‘/api/users’, userRoutes)
  • Use the findOne() method on the User model to get the user’s object from the database.
  • Password needs to be encrypted before checking as we are storing encrypted passwords in the database, so add a method on the User Model itself. Edit models/userModel.js and add a method on the userSchema – userSchema.methods.matchPassword.
  • Use this new method in userController.js and finished the implementation.
  • Don’t return the token for now. Just set it to null. Return all other details leaving the password as a json object and also add an else condition.
  • Test this new endpoint in POSTMAN. (start only the server for now)

32. Using Json Web Tokens (JWT)

  • What are JWTs and how do they work?
  • Installation: npm install jsonwebtoken
  • Create a folder called backend/utils. Put all helpers and utility functions here. Inside it create a file named generateToken.js and create the token generation function. Also add the JWT_SECRET to the env as this is needed for the token generation.
  • Import generateToken.js into userController.js and use the function in the response object’s token property (key).
  • Test in Postman. Add this request to Postman.

33. Creating custom Authentication Middleware to accessprotected routes.

  • Add a new request in Postman. GET /api/users/profile with request URL {{URL}}/api/users/profile.
  • Add getUserProfile controller method to userController.js and also export it. Also add the route for this in userRoutes.js.
  • Create a new file named middleware/authMiddleware.js. This middleware will validate the token.
  • Implement the protect middleware function. In our backend we will be getting the authorization tokens in the header object in requests (we will send it that way from React).
  • Import protect into routes/userRoutes.js. We need to add our middleware function here to the /profile endpoint.
  • Implement the complete of the protect middleware function.
  • Once done, we can now use this middleware to any endpoint (route) that we want to be protected, that is only accessible using a valid JWT.
  • Finish implementation of the getUserProfile controller function in userController.js
  • Save the token in Postman, so we don’t have to keep copying and pasting tokens to the Headers. Add Tests to login request so that the token can be set in an environment variable. After that set profile request Auth Type to Bearer Token.

34. User registration

  • Add a new request to Postman: POST /api/users with url as {{URL}}/api/users. This will be a POST request. So a GET request to the same endpoint will give us a total list of users, while a POST request will create a new user.
  • Add a new registerUser controller function to the userController.js file. After that, import this function to userRoutes.js and create a new register route.
  • #### Password Encryption ####
  • The password still isn’t encrypted as we sent it directly to the User.create() function. So to encrypt password while creating a new user and adding it to the database, create a new mongoose middleware.
  • In mongoose, we can set certain things to happen on saves or finds etc. So when we execute the User.create function, before saving to database, we can run some code to encrypt the password and then save.
  • Test the new endpoint in Postman.

35. User Login Reducer and Action

  • Add all constants for the login. Create the file constants/userConstants.js and add all the constants.
  • Create the reducers/userReducer.js file and add the userLoginReducer function. Add all the necessary actions and logic.
  • Import userLoginReducer to store.js and add it to the combineReducers function’s parameter object.
  • Create the actions file in actions/userActions.js and add the action logic. This is pretty much the same as the earlier actions. Only difference here is that we have to add some headers to the axios request, and also store the user data to localStorage.
  • Lastly, since we stored the user data in localStorage, we should load them in the initial state in store.js. Create a variable named userInfoFromStorage and set it to get it’s value from localStorage. In the initialState variable, add another key named userLogin and set it’s value to userInfouserLogin: { userInfo: userInfoFromStorage }

36. User Login Screen

  • Create a new component called components/FormContainer.js which will just be a simple wrapper for our form elements. Just a box with some styling, which we will use to add all our forms in.
  • Create a new screen in screens/LoginScreen.js and write the ui and logic.
  • Import it in App.js and create a route for it.
  • (styling changes overall if required)

37. Implement all the Login – Redux functionality in the LoginScreen component.

38. Header modification to show User and User Logout feature

  • Modify Header.js. Import redux modules, for running the LOGOUT action and getting access to the state.
    import {useDispatch, useSelector} from ‘react-redux’
  • Import Menu, MenuButton, MenuList, MenuItem from Chakra.
  • Get the userInfo state using useSelector.
  • Also import import { IoChevronDown } from ‘react-icons/io5’
  • Create a logout action in userActions.js.
  • Implement all the logic.

39. User Register, Constants, Reducer, Action and Screen.

  • Add new REGISTER constants to the userConstants.js
  • Create userRegisterReducer in the userReducers.js
  • Import this reducer in store.js and add it to combineReducers
  • Create register action in userActions.js
  • Create the RegisterScreen component and add it to the App.js router.

40. Update User Profile endpoint in the backend

  • Create a updateUserProfile controller method and export it.
  • Import updateUserProfile in userRoutes.js and add a PUT request on the same /profile route. This route will also take the middleware protect as this is a protected endpoint.

41. User Profile Screen and Getting User Details

  • Add USER DETAILS constants to the userConstants.js file.
  • Create userDetailsReducer in userReducer.js and import and add it to the Store.
  • Create and add a getUserDetails action in userActions.js
  • Create the ProfileScreen and add it to Router in App.js

42. Add Update User Profile functionality

  • Add new UPDATE PROFILE constants to the userConstants.js
  • Create userUpdateProfileReducer in the userReducers.js
  • Import this reducer in store.js and add it to combineReducers
  • Create updateUserProfile action in userActions.js

43. Shipping Screen and Save Address

  • Create a new component/screen in screen/ShippingScreen.js and add it to the Router in App.js
  • Complete the ShippingScreen component. Create all the local state required and build the shipping form.
  • In the submitHandler we want to dispatch an action that will save the shipping address to the Redux store.
  • Create a new constant named CART_SAVE_SHIPPING_ADDRESS in the constants/cartConstants.js file.
  • Create a new action named saveShippingAddress in the actions/cartActions.js file.
  • Create a new case CART_SAVE_SHIPPING_ADDRESS in the reducers/cartReducers.js file. Also in the cartReducer function’s initial state object, add another key named shippingAddress and set it to an empty object.
  • Since we are going to store the shippingAddress to localStorage, we also should check if it’s already present in the user’s machine and load it if present. Add the code to the store.js file.
  • Add all Redux related functionality to the ShippingScreen component and finish the implementation.

44. Checkout Steps Component

  • Create he component and then add it to the ShippingScreen component.

45. PaymentScreen – where users can choose the payment method

  • Create the PaymentScreen component in the screens folder.
  • Add CART_SAVE_PAYMENT_METHOD to the cartConstants.js file.
  • Create the savePaymentMethod action function in actions/cartActions.js file.
  • Create a new case CART_SAVE_PAYMENT_METHOD in the reducers/cartReducer.js
  • Import and add PaymentScreen to App.js router.

46. Place Order Screen

  • We will just create a basic screen/page for now. We will do all the real setup only once we have created a backend to actually accept an order.
  • Create a new screen named PlaceOrderScreen.js in the screen folder.
  • Complete the PlaceOrderScreen implementation for now. We will complete this fully when we are done with our order functionality in the backend.
  • Also calculate and set cart.itemsPrice, cart.shippingPrice, cart.taxPrice, cart.totalPrice

47. Backend: Order controller and endpoint (route)

  • Create controllers/orderController.js.
  • Create routes/orderRoutes.js. Import the orderController and connect it here to a endpoint.
  • Lastly add the main endpoint (route) to server.js

48. Create Order

  • Create an constants/orderConstants.js file and add all the constants.
  • Create a new reducer file in reducers/orderReducers.js and add a orderCreateReducer function in it. Import this in store.js and add it to combineReducers.
  • Create a new actions file in actions/orderActions.js and add a createOrder action function.
  • Import createOrder action into the PlaceOrderScreen component and complete the implementation.

49. Get Order By ID (Backend Endpoint)

  • Create the getORderById controller function in the orderController.js file.
  • Add ‘/:id’ route to the orderRoute.js file and attached it to the getOrderbyID controller function.

50. Create the order details reducer and action (frontend)

  • Add new order details related constants in the orderConstants.js file.
  • Create orderDetailsReducer to the orderReducer.js file and connect it in the store.js file.
  • Create a new getOrderDetails function in the orderActions.js file.

51. Create the Order Screen component

  • Create the OrderScreen.js file in screens.
  • Add this new screen to the App.js route.

52. Backend endpoint for updating an order to paid

  • Create a new updateOrderToPaid controller function in the backend/controllers/orderController.js file.
  • Import updateOrderToPaid in the routes/orderRoutes.js and add a route for the endpoint ‘/:id/pay’ making it a PUT request.