| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Hi, This is course page of CoderDost Youtube Channel React JS 2023 Course Video Link ,
Git Commands
use git clone <repository_url>
checkout branch according to Chapter number git checkout react-1
run npm install inside the root directory before running the code
If you are not comfortable with git, directly download the branch as Zip.
Choose branch related to the Chapter e.g. react-1
run npm install inside the root directory before running the code
Assignment 1 : If we delete node_modules. How to run our app again successfully ?
Assignment 2 : How to remove double console.logs from React ? [ it is not needed in real life to remove them, its just an assignment problem ]. [ Hint: Some special Component at top level is of App is causing it ]. We explore more about - why this is needed in later videos.
Assignment 3 : Create a Page with multiple React Apps. Both React Apps should be independent of each other.
Assignment 4 : Try to build a react app using other toolchains like Vite
Assignment 1 : Create a simple React app for RESUME Builder. It will be static website. You have to make components like Resume as top level and under it - Skills, Education, Experience etc as components. All resume data will be under 1 big JavaScript object like which you can us in components via props. You can fix the number of items in Skills, Education, Experience or any section. Example you can say that only 3 experience items is allowed.
resume = {
experience : [ { year:2012, company:'xyz', role:'something' }],
education:[ ],
skills : [ 'react js', 'node js']
.....
...
}You can choose any simple HTML layout and convert it to React Components
Example Link : Resume HTML
Assignment 2 : Create a Parent Component called Border which can provide some CSS border to any component nested into it. [Hint : You will need to use children props here
< Border>
< Component >
< Border />< List layout="numbered" items={items}/>
< List layout="alpha" items={items}/>
< List layout="bullet" items={items}/>Assignment 2 : This is continuation of previous assignment RESUME Builder
resume = {
experience : [ { year:2012, company:'xyz', role:'something' }],
education:[ ],
skills : [ 'react js', 'node js']
.....
...
}You can choose any simple HTML layout and convert it to React Components
Example Link : Resume HTML
Assignment 1 : Make a simple page with 1 Image, 1button, 1 form Input text box and try to apply these events .
Assignment 2 : Make a form using < Form> tag and put an textbox and button inside this form. try to click the button after entering into textbox. Does form reloads ? Can you try to stop is using e.preventDefault. Try it.
Assignment 3 : use an Input Textbox : after you enter some text. try to press ENTER button and show the an alert or console.log. You can capture the onKeyPress event, button how you will you make it work only for "Enter" ? It should not work on pressing of other keys. [Hint: Explore the synthetic event object ]
Assignment 4 : This is continuation of previous assignment RESUME Builder.
Assignment 5 : Can you try the challenge of passing the function in one Prop like onPlay and the message inside that function to be accessed from other prop message [ As shown in Chapter Video ]
Assignment 6 : Using event bubbling concept print the name of Parents to Child of any clicked element. It should be order in "GrandParent >Parent > Child" this kind of order. Where "Child" represents the current clicked element.
Assignment 7 : Make a custom event called onClose. this event should close the current browser tab. you can apply it to a button on click or anywhere.
Assignment 1 : Make a digital CLOCK Component using useEffect Hook. We need to only update the time Upto seconds in it. HH:MM:SS format can be used. Can you make it send a Console.log at end of every minute ?
Assignment 2 : Implement a simple TIMER that displays the elapsed time since the start button was pressed, and it can be stopped and reset. Like a stopwatch.
const nations = [
{ name: 'India', value: 'IN' },
{ name: 'Pak', value: 'PK' },
{ name: 'Bangladesh', value: 'BG' },
] Assignment 2 : FILTERED LIST : Make a List of something using an Array (a list can of cricket player /countries/ movie name etc). Now make this list it searchable, you have to put a input textbox at top of list. When you type in textbox it should only show you items matching from text typed. For example - If you type only "in" it should show things like "India" / "China" as both have in in it.
Assignment 2.1 : FILTERED LIST : Make above List as separate components for List, Input form and pass the states from each other using concepts learnt till now.
Assignment 3 :
This is continuation of previous assignment RESUME Builder. Now you have to make a separate component ResumeEditor which has a FORM. This form will have many input boxes. Each one related to one section. For example you can have one input box or experience section. Another input box for skill section and like this. Every input box should have an Add button in front of it. Once you press this add button that information is stored in the state , which you can update at top of the App level. Now this state should update the Resume Component and its child you have built.
first component will be your RESUME document which is only for reading purpose.
second component will be this FORM
you have to manage the state in between
only Add functionality is required in this assignment
you can change input boxes according to your need depending on your format of Resume. You can have multiple textboxes also for same section. Like for date + experience item etc.
Assignment 4 : Try this challenge : https://beta.reactjs.org/learn/state-a-components-memory#challenges
Todo app can be used to maintain a list of your pending daily items. A Simple todo list must have these features
KEYBOARD BASED Features :
Other Features :
Advanced Features :
ANIMATION BASED Features [optional] :
Assignment 1 : The method shown in this video was just to introduce useEffect hook. However that was not the correct use of useEffect hook. Can you change the code to remove useEffect and still have the editVideo functionality. [ Hint : use the concept that Component is rendered every time prop changes ]
Assignment 2 : This is continuation of previous assignment RESUME Builder.
Assignment 1 : Try this challenge : https://beta.reactjs.org/learn/extracting-state-logic-into-a-reducer#challenges
Assignment 2 : Convert your RESUME BUILDER Application from useState to useReducer by converting states logic to a common reducer. Your reducer can have as many switch cases as you want. You can also divide them based on sections. ADD_SKILL, ADD_EXPERIENCE etc. to make logic even simpler for developer.
Assignment 1 : Try this challenge : https://beta.reactjs.org/learn/passing-data-deeply-with-context#challenges
Assignment 2 : Add a Context to your RESUME BUILDER to change font-size, font-color and some other font-properties. Also add a form to changed these property at top of App.
Assignment 3 : Add a Context to your RESUME BUILDER to change Dark Mode and Light Mode. You can also use a React Switch kind of library to make it more user friendly to switch.
const [count, increment, decrement] = useCounter(0);https://beta.reactjs.org/learn/referencing-values-with-refs#challenges
Assignment 2 : Try this challenge:
https://beta.reactjs.org/learn/manipulating-the-dom-with-refs#challenges
Assignment 3 : Make a useWindowSize Hook: which returns size of current browser window.
const [width, height] = useWindowSize();https://beta.reactjs.org/learn/synchronizing-with-effects#challenges
https://beta.reactjs.org/learn/removing-effect-dependencies#challenges
https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks#challenges
You have to create a button which can get some posts and show them in a List.
You have to a show comments button on each list item. On click of show comments, Post's comments should be fetched below that list item. [ Comments are available for each post in API]
When you click on a particular list item's show comments, it should expand and show comments, otherwise it should collapse and hide the comments.
Try to optimize by :
Assignment 1 : Implement a component that displays a list of items. The component should memoize the list of items to prevent unnecessary re-rendering.
Assignment 2: How to use memoization in the JSON Placeholder API assignment in previous problem. Can you try to optimize it using useMemo/useCallback ?
Assignment 3: useMemo and useCallback are same hook. useCallback is just a convenient hook way to write useMemo for functions. Prove this using useMemo in place of useCallback in any previous problem. [ Hint : you will have to change the useMemo callback and return the function definition ]
--- END OF REACT COURSE ------
Hi, This is course page of CoderDost Youtube Channel NODE JS 2023 Course Video Link
You can download code in 2 ways :
Git Commands
use git clone <repository_url>
checkout branch according to Chapter number git checkout node-1
run npm install inside the root directory before running the code
If you are not comfortable with git, directly download the branch as Zip.
Choose branch related to the Chapter e.g. node-1
run npm install inside the root directory before running the code
NOTE : Code for React JS app is available in final code node-12 branch in folder react-app. It can be used in previous chapters also like chapter-8 etc (however it's the final code, so step-wise code is not available for React, However one can follow the tutorial and make it , sorry for inconvenience)
- CommonJS Module
//lib.js
exports.sum = function(){}
//index.js
const module = require('./lib.js')
module.sum();- ES Module
//lib.js
export {sum}
//index.js
import {sum} from './lib.js'
FileSystem Module(fs) is one of core modules of Node JS. fs can be used to read/write any file. There are many more core modules in NodeJS which you can check in NodeJS API docs.
Reading files can be Synchronous or Asynchronous. Async is most preferred method in NodeJS. As there is NO blocking of I/O in NodeJS
Node project can be initialized with npm init command which also creates package.json file
package.json is a configuration file for node projects which has scripts, dependencies, devDependencies etc
npm install <package-name> is used to install any online modules available for node on NPM repository online.
nodemon is a package for running node server and track live changes to re-start again.
scripts inside package.json can be used like npm run <script-name> e.g npm run dev. Only for npm start you can avoid run.
use npm install -g <package.json> to install packages globally on your system. Not just in the project but useful all over your system.
Node versions are formatted like 4.1.9 where these are major.minor.patch versions.
you can install all dependencies again using npm install again
package-lock.json has exact versions installed and link of dependencies of each package.
use npm update to update packages safely. npm outdated shows outdated and latets versions of packages installed in your package.json
use npm uninstall <package-name> to uninstall packages from package.json
node_modules should not be shared - you can make .gitignoreto ignore them to be uploaded.
Request object comprises of many properties, but important ones are :
Response object comprises of many properties, but important ones are :
HTTP requests and responses can be tracked from Dev Tools > Network Tab
In Node, we can use core http module to create a Server which listens to requests, modify data in-between and provides responses. Server needs a PORT to be bound to - use only port number > 1024.
Server can simply be said as a function which receives a request and returns a response. [ This is just for understanding]
There are many Headers which exists on request and responses - shared a link below with list of existing headers.
We can use Server to do 3 things:
Every Request has one and only one response. If there is more than 1 response which you want to send - you will encounter a error - "Headers already sent"
POSTMAN is a software for doing complex API requests.
ExpressJS is de-facto Node framework - and used in most Node applications which are used as web server.
You can install express npm install express
Express has few level of methods :
Response methods (res is our response objects)
HTTP Request Types we generally use :
API / Endpoints / Routes are used inter-changeably but they are related to server paths.
Middle-ware : Modifies the request before it reaches the next middleware or endpoints.
Sequence of middleware is very important, as first middleware is first traversed by request.
Middle-wares can be used for many use cases, like loggers, authentication, parsing data etc.
Middle-ware can be :
Request properties (req is our request object)
Static Hosting : we can make 1 or more folders as static hosted using express.static middleware. server.use(express.static(< directory >)) Static hosting is like sharing a folder/directory and making its file readable as it is. Note : index.html is default file which would be read in a static hosted folder, if you don't mention any file name.
3 major ways of sending data from client to server via request are :
1. Send data via URL in Query String
This is easiest method to send data and mostly used in GET request.
When you have URL with ?name=Youstart&subject=express at end, it translates in a query string. In query string each key,value pair is separated by = and between 2 such pairs we put &.
To read such data in express you can use req.query :
server.get("/demo",function(req,res){
console.log(req.query) // prints all data in request object
res.send(req.query); // send back same data in response object
})Make above server with API endpoint /demo as shown above :
Try to call this API in your browser http://localhost:8080/demo?name=Youstart - this will return a response of req.query JSON object
Create 3 query parameters name, age, subject with some values. Check the final output of req.query - can you find all data on server side. Can you send it back to client via res object.
2. Send data via Request Params
In this method you can have a URL with url path like /Youstart/express at end it translates in a param string. In param part string each value is separated by /. As you can see that URL only contains value not the key part of data. key part is decided by the endpoint definition at express server
server.get("/demo/:name/:subject",function(req,res){ console.log(req.params) // prints all data in request object res.send(req.query); // send back same data in response object })
So sequence of values matter in this case. As values sent from client are matched with name and subject params of URL later.
Make above server with API endpoint /demo as shown above :
Try to call this API in your browser http://localhost:8080/demo/Youstart/Express - this will return a response of req.params JSON object
Create 3 URL params name, age, subject . Call the URL and check the final output of req.params - can you find all data on server side. Can you send it back to client via res object.
3. Send data via Request Body
Final method of sending data is via body part of request. We can send data directly to body using URL. We have to either use one of these methods
Use a HTML Form and make method value as POST. This will make all name=value pair to go via body of request.
Use special browsers like POSTMAN to change the body directly. (We will see this example in next classes)
server.post("/demo",function(req,res){
console.log(req.body) // prints all data in request object
res.send(req.body); // send back same data in response object
})The HTTP method is the type of request you send to the server. You can choose from these five types below:
GET : This request is used to get a resource from a server. If you perform a GET request, the server looks for the data you requested and sends it back to you. In other words, a GET request performs a READ operation. This is the default request method.
POST This request is used to create a new resource on a server. If you perform a POST request, the server creates a new entry in the database and tells you whether the creation is successful. In other words, a POST request performs an CREATE operation.
PUT and PATCH: These two requests are used to update a resource on a server. If you perform a PUT or PATCH request, the server updates an entry in the database and tells you whether the update is successful. In other words, a PUT or PATCH request performs an UPDATE operation.
DELETE : This request is used to delete a resource from a server. If you perform a DELETE request, the server deletes an entry in the database and tells you whether the deletion is successful. In other words, a DELETE request performs a DELETE operation.
REST API are a combination of METHODS( GET, POST etc) , PATH (based on resource name)
Suppose you have a resource named task, Here is the example of 5 REST APIs commonly available for task.
GET \tasks : to read all
GET \task\:id : to read a particular task which can be identified by unique id
REST API ( CRUD - Create , Read , Update, Delete) :
CREATE
READ
UPDATE
DELETE
MVC (Model-View-Controller) is a pattern in software design commonly used to implement user interfaces (VIEW), data (MODEL), and controlling logic (CONTROLLER). It emphasizes a separation between the software's business logic and display.
In Our Project this will be : Model - Database Schema's and Business logics and rules View - Server Side Templates (or React front-end) Controller - functions attached to routes for modifying request and sending responses. It's a link between the Model and View.
Router
Arrange Directory in Server like this :
Controllers - file containing functions which are attached to each route path Routes - files containing routers Models : to be discussed in later chapters Views: to be discussed in later chapters
MongoDB is NoSQL database which has a JSON like (BSON data) data storage.
After installing MongoDB community server package on your system - you will have to start the database server using command :
mongodThis will start MongoDB server on default port 27017. You might have to create a directory for storage in MongoDB - if server asks for storage directory
Once server is started - you can use mongo client to connect to local server
mongoNow you can use several commands to work with database:
show dbs
This will list all the database in your system
use <dbname>
This will command will let you switch to a particular
Hostname is Database server address - like localhost or db.xy.com. In mongoDB hostname generally uses mongodb protocol to connect. So URLs are generally are of shape : mongodb://localhost:27017
Database are topmost storage level of your data - mostly each application has 1 database - however complex application might have more than 1 databases. Database is something like university database
There can be many collections inside a database - collection is a group of documents of similar kind - students, teachers, courses etc
Finally document is basic entity of storage in Mongod, it looks very similar to an object in JSON. (However it is BSON)
Mongo DB community server comes with in-bulit Mongo CLI which can act as a terminal based client. You can use the CRUD functionality from here
Read the commands here
These utilities comes with community server and can be found in CMD/terminal. They are not the part of Mongo CLI client.
mongodump --db accounts Above command takes backup of database accounts and stores into a directory named dump
mongorestore --db accounts dump/accounts
Above command restore your database accounts from backup directory dump
Task : Use these commands on terminal/CMD (not inside mongo client)
Take a backup of database you created in assignment 1.
Restore the backup of database from dump directory.
To install MONGODB NODE.JS DRIVER use this command
npm install mongodbYou can setup database in Node server using following commands :
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
});Now this db handle can be used to perform any CRUD operation using MongoDB NodeJS driver.
Mongo Server
mongod --dbpath <path-to-db-directory>
Mongo Compass : UI Client to see mongo server (local or remote)
Mongo Shell : Command-line based mongo client for checking mongo database.
Some Mongo Commands:
(run from anywhere inside the shell)
(run only from inside a database)
filter Object : { fieldName : {operator: value}} fieldName : database fields name operator : $eq = equal , $gt= greater than, $lt : less than, $gte = greater than equal, $and and $or operator value : what value we are comparing with operator.
e.g { age : {$gt:5}}. - age is greater than value 5
Cursor functions : These are applied to find() query .
Upsert : Update + Insert, when we want a new info to create a new obejcts if no existing object matches filter queries.
Projection
MONGO ATLAS CLOUD SETUP : Check the video in tutorial
** Enviroment Variable** : To use environment variable we can use a npm package called dotenv which will create new process.env variables.
Mongo Atlas Setup Detailed Video
You can install mongoose using npm :
npm install mongooseAfter installing , you can import mongoose to your project :
const mongoose = require("mongoose");To connect mongoose to your database test, you have to use the following commands :
var mongoose = require('mongoose');
await mongoose.connect('mongodb://127.0.0.1:27017/test');Connection can also be stored in a variable to check whether it is connected properly or not. Also to disconnect database later on. You can read more details Here
Schema is the specification according to which data object is created in Database.
taskSchema which contains title, status, date fields. So every task object saved in database will have these 3 fields according to Schema given
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const taskSchema = new Schema({
title: String,
status: Boolean,
date: { type: Date, default: Date.now }
});Many types of data are allowed in Mongoose Schema. The common SchemaTypes are:
You can put a lot of conditions inside the Schema object :
age: { type: Number, default:18, min: 18, max: 65, required :true }
// default value of Number is 18 and should be between 18-65, and can't be null or emptyDetailed information on SchemaTypes is Here
Model are similar to classes, they create a Class from Schema. These classes(i.e Models) can be used to create each new database object.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const taskSchema = new Schema({
title: String,
status: Boolean,
date: { type: Date, default: Date.now },
});
const Task = mongoose.model('Task', taskSchema); //Task Model to create new database objects for `tasks` Collection
Connect mongoose to a database named todolist if you don't have a database with this name. Mongoose will create it after you perform any insert operation.
Creata a Schema named taskSchema and model named Task as shown above.
To Create new obejct in database we can use new keyword and create an object from Model. We can use save() function to save the object in database. Unless, you call save function - the object remains in memory. If your collection not yet created in MongoDB, it will created with name of Model pluralized (e.g Task will make a collection named tasks)
server.post("/task",function(req,res){
let task = new Task();
task.title = "shopping";
task.status = true;
task.date = new Date();
task.save();
})You have to create an API Endpoint to type POST named /task. It will create a new task item in database whenever called properly. All 3 fields title, status, date must be mandatory (required). If someone is not passing all fields properly, no database entry should be created.
//request body :
{
"title" : "task1",
"status" : true,
"date" :'2010-05-30"
}
// response body should return the newly created object.
res.json(task);Check using Mongo Compass/or Mongo Shell that new record in database is created. Also check name of collection. Is is tasks ?
To read new obejcts from database, one can use find query or similar queries. find queries also contain some conditions which can restrict what kind of data objects you want to read from database.
server.get("/task/:name",function(req,res){
Task.findOne({name:req.params.name},function(err,doc){
console.log(doc) // this will contain db object
})
})
server.get("/tasks",function(req,res){
Task.find({},function(err,docs){
console.log(docs) // this is an array which contains all task objects
})
})
You have to create an API Endpoint to type GET named /tasks. It will return all task available in collection tasks.
//request is GET so no data in body :
// response body should return the all db objects of collection tasks.
res.json(tasks);Check Mongo Compass/or Mongo Shell - if all records are returned in response. How you will change this API to make it return only one database record in which title is matched with title sent in request query.
To Update an existing object in database we need to first find an object from database and then update in database. This might be considered as a combination of find and save methods.
There are generally 2 cases in update :
First scenario is covered using this query. Here you are overwriting all properties and resulting object will only have name property.
server.put("/task/:name",function(req,res){
Task.findOneAndReplace({name:req.params.name},{name:'YouStart'},{new:true},function(err,doc){
console.log(doc) // this will contain new db object
})
})Second scenario is covered using this query. Here you are only changing value of name property in existing object without changing other values in Object.
server.put("/task/:name",function(req,res){
Task.findOneAndUpdate({name:req.params.name},{name:'YouStart'},,{new:true},function(err,doc){
console.log(doc) // this will contain db object
})
})You have to create an API Endpoint to type PUT named /task/:id. It will update existing task item in database which has ObjectId set to id you have passed.
//request params will have id in URL path :
{
"title" : "task-changed",
}
// response body should return the newly updated object.
res.json(task);Check using Mongo Compass/or Mongo Shell that only title of record in database is changed. All other properties remain the same.
To Delete existing object from database we need to first find an object from database and then delete. This might be considered as a combination of find and delete methods.
server.delete("/task/:name",function(req,res){
Task.findOneAndDelete({name:req.params.name},function(err,doc){
console.log(doc) // this will contain deleted object object
})
})You have to create an API Endpoint to type DELETE named /task/:id. It will delete existing task item in database which has ObjectId set to id you have passed.
//request params will have id in URL path :
// response body should return the deleted object.
res.json(task);Check using Mongo Compass/or Mongo Shell that the record is deleted or not.
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/test');
// use `await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');` if your database has auth enabled
}const productSchema = new Schema({
title: {type: String, required: true, unique: true} ,
description: String,
price: {type: Number, min:[0,'wrong price'],required: true},
discountPercentage: {type: Number, min:[0,'wrong min discount'], max:[50,'wrong max discount']},
rating: {type: Number, min:[0,'wrong min rating'], max:[5,'wrong max rating']},
brand: {type: String,required: true},
category: {type: String, required: true},
thumbnail: {type: String, required: true},
images: [ String ]
});const Product = mongoose.model('Product', productSchema); const document = new Product();
// document is actually saved in database after save()
await document.save();Mongoose Schema/Model can act as Model of Model-View-Controller concept.
CREATE :
const product = new Product();
await product.save()READ :
const products = await Product.find();
const products = await Product.find({price:{$gt:500}});const product = await Product.findById(id);UPDATE :
const doc = await Product.findOneAndReplace({_id:id},req.body,{new:true})const doc = await Product.findOneAndUpdate({_id:id},req.body,{new:true})DELETE :
const doc = await Product.findOneAndDelete({_id:id})Assignment 1 : Make a Schema for user with userSchema which has these conditions :
Create addressSchema needed in above example as :
Now try to create this user object and save it to database.
Queries in Mongoose : Link
Sending data from front-end to Server
CORS Issues :
CORS - Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy
const cors = require('cors');
server.use(cors())HTML Forms
you can use build folder of react and add it to static hosting of express. server.use(express.static('build'));
use wildcard in express route to point to React single page applications (index.html)
res.sendFile(path.resolve(__dirname,'build','index.html'))__dirname is a variable
Preparation for deployment
Server side rendering is done using many templating languages
We have used EJS which is one of the most popular one.
Install npm install ejs
<% if (product) { %>
<h2><%= product.title %></h2>
<% } %>For passing variable to template engine and render a new page :
const ejs = require('ejs');
ejs.renderFile(path.resolve(__dirname,'../pages/index.ejs'), {products:products}, function(err, str){
res.send(str); // this is the rendered HTML
});`npm install jsonwebtoken`
jwt.sign(payload, secret) this returns a token
jwt.verify(token, secret) this returns decoded value of payload
We will use HTTP Authorization headers for exchanging these tokens e.g. Authorization = 'Bearer JWT_TOKEN_VALUE'
Using RSA algorithm (public-private key) : check video.
you can use a library like bcrypt to hash password, so they are not stored in plain text format
npm install bcrypt
bcrypt.hashSync(userProvidedPassword, saltRounds)
bcrypt.compareSync(loginPassword, AlreadyHashedPassword)
return true of false based on verification of password
Session middleware is used to store session variable for each user on server side. This middleware can make use of any data storage depending on settings. By default it stores session variables in Memory (RAM).
First install express-session middleware
npm install express-sessionNow you can use it in your express server
var server = express()
const session = require('express-session')
server.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: false } // make secure : true incase you are using HTTPS
}))Now you can use req.session object to store any value for a particular user in server session. This value will not interact with similar variable of other users.
server.get('/user', function(req, res) {
if (req.session.views) {
req.session.views++
res.json({views:req.session.views})
} else {
req.session.views = 1
res.send('welcome to the session demo. refresh!')
}
})In above example we are initializing a variable session for each user. Write similar code in your server
Sorting:
find().sort({fieldname: 1}) // ascending can be 1, asc, ascending , Descending values can be -1, desc, descending
Pagination related queries:
find().limit(pageSize).skip( pageSize*(pageNumber-1)) // where pageSize is number of document results you want to show.
Population
Populate() lets you reference documents in other collections.
const userSchema = new Schema({
firstName: { type: String, required: true },
lastName: String,
cart:[{ type: Schema.Types.ObjectId, ref: 'Product' }],
email: {
type: String,
unique: true,
validate: {
validator: function (v) {
return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(v);
},
message: (props) => `${props.value} is not a valid email!`,
},
required: true,
},
password: { type: String, minLength: 6, required: true },
token: String,
});
//cart populated example
const user = await User.findById(id).populate('cart');For More details : Detailed Population Video
const em = new EventEmitter()
em.on(eventName, (payloadData)=>{} ) // listeners
em.emit( eventName , payloadData ) // emit eventsA readable stream
const rr = fs.createReadStream('./data.json');
rr.on('data', (data) => { // received data event on every file read
console.log({data});
});
rr.on('end', (data) => { // received end of stream event
console.log({data});
});npm install socket.io
const server = express();
const app = require('http').createServer(server);
const io = require('socket.io')(app);
io.on('connection', (socket) => {
console.log('socket',socket.id)
socket.on('msg',(data)=>{ // listener to client-side events 'msg'
console.log({data})
})
socket.emit('serverMsg',{server:'hi'} //emitting 'serverMsg' for Client-side
});
app.listen(port)// embeding client-side library which will be downloaded from module installed on Server
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
console.log('socket',socket.id)
socket.emit('msg',{player:'one'}) // emitting 'msg' to server-side
socket.on('serverMsg',(data)=>{ // listener to server-side events 'serverMsg'
console.log({data});
})
</script>------------END OF COURSE---------------------
An online resume generator application will able to generate resume for students and professional based on their input data. We will have options of downloading the resume or hosting the resume on a particular URL (which user can share). Users will be able to choose between many Template designs for their resume. User data will be stored in database and can be edited later on.
Tic Tac Toe is quite ubiquitous popular game. We have a 3 x 3 grid with traditional cross and circle notation. However playing tic tac toe with a distant friend connected via social media is a dream come true. Here is the simple game :
An Amazon like store to find and buy things. The site will have to interface one for admin and other for general users :
User site features :
Admin site features :
PhotoGram Project is a web app similar to instagram. Purpose of app is to store your photos in an album and add some filters. Users can login and browse their old photos, search them by name, sort using name/date added etc. They can also apply instagram style filters to their photos.
Features :
PokeMon requires your help. Save them by picking the right ones. There are some good characters and there are the bad ones. Create a 8×8 Div to make a gameboard.
Game Rules (Offline)
Game Rules (Online)
Multi-user chat will be a web application where users can chat privately or in group chat.
Chat bots are the need of the time. With too much information overload and lots of application to interact with - humans need a way to interact with devices in more human way. Chat bots makes your life easy by putting up intelligent question, suggestions and making choice simple enough. We are designing a chat bot which may diagnose simple disease or common problem with health.
Admin Panel
Examinee side
This app can be used to manage expenses between friends who are planning an event/trip/party. This app will help in adding all expenses done by any individual. It will provide the report of who owes how much and money should be given to whom.
Features :
Refer to this URL
https://zapier.com/blog/best-pomodoro-apps/
When you visit a restaurant you have to book a table for people. If you book in advance, restaurant has to plan according to available options.
Appointment book app creates and event in which you can book slots. It can help a professional like doctor, interviewer to provide slots to other person in which they can visit. Calendly site is a good example of such an app
This news application will be something similar to google news and will pull news from major news channels and apis.
Make an advanced interface for creating memes! Allow the user to upload an image, write a caption, and build a meme with the Imgflip api. To take it to the next level, allow the user to share their meme on Twitter, Facebook, and other social platforms.
Example : Check this
It is easy to make travel booking for direct journey from one city to another. But in case you don't find direct flights, trains etc. You might have to break the journey and find trains from a intermediate station and change from their to get to end destination.
Hi, This is course page of CoderDost Youtube Channel Redux JS 2023 Course Video Link ,
use git clone <repository_url>
checkout 'redux' branch - All Chapters are in same branch but different folders git checkout redux
run npm install inside the each folder before running the code
Choose branch related to the Redux e.g. react. It contains all chapter
run npm install inside each chapter folder before running the code
Assignment 1 : Using the concepts learnt in this chapter. Make a Async type of call from a new reducer to any online API like JSON Placeholder Posts. Also show proper loading messages in console. Like - loading posts..., posts loaded , posts fetching failed. Also add those posts to a state of reducer in a sorted manner (sort by title)
Assignment 2 : Check out IMMER library and run some example and see how you can make mutating updates like state.amount++ inside reducer logic. And still it work perfectly in redux. Immer Link
Assignment 1 : Add more cases in Account Reducer called decrementByAmount . Also check that amount should not be decremented in case amount to be decremented is less than account Balance. For e.g. if total amount in account is 10, you can't decrement by 11. Also show an error in that situation to user.
Assignment 2 : Check out IMMER library and run some example and see how you can make mutating updates like state.amount++ inside reducer logic. And still it work perfectly in redux. Immer Link
Assignment 1 : Add more cases in Account Reducer called decrementByAmount . Also check that amount should not be decremented in case amount to be decremented is less than account Balance. For e.g. if total amount in account is 10, you can't decrement by 11. Also show an error in that situation to user.
Assignment 2 : Create more async thunk examples, we only tried GET USER- READ example. But try the CRUD example to Create new user, Update the user, Delete the user. - You have to create a list of users which has names of all users in local database - You an INPUT BOX to add new users to list , users show also add to database and updated in list.[Hint: use REST API concepts for Create API, POST method] - You can put a delete button on end of list item. On clicking of this button user list item will be deleted from database. [Hint: use REST API concepts Delete API, DELETE method] - You can put a selected button on end of list item. On clicking of this button user list item will change colors. [Hint: use REST API concepts Update API, PUT/PATCH method] -
| Back | FazBrowse Home | New Git URL |