0% found this document useful (0 votes)
14 views

ecommerce project

The document outlines the development of Shopease, a full-stack ecommerce website, detailing its major features such as a search bar, filtering options, product recommendations, and a payment gateway. It describes the backend and frontend structure, including authentication, routing, and user roles, as well as technical implementations like JWT for secure authentication and bcrypt for password encryption. Additionally, it addresses performance optimization strategies for filtering and searching products, as well as handling scenarios like no search results and fuzzy matching for misspelled queries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

ecommerce project

The document outlines the development of Shopease, a full-stack ecommerce website, detailing its major features such as a search bar, filtering options, product recommendations, and a payment gateway. It describes the backend and frontend structure, including authentication, routing, and user roles, as well as technical implementations like JWT for secure authentication and bcrypt for password encryption. Additionally, it addresses performance optimization strategies for filtering and searching products, as well as handling scenarios like no search results and fuzzy matching for misspelled queries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Project Revision

Project intro. :

1. My rst project is Shopease , which is a full stack ecommerce website designed for seamless
shopping experience

I have worked on 4 major features

1. Search bar
2. Filter option based on category and price
3. Similar product recommendation feature
4. Braintree payment gateway

This project helped me alot to strengthen my skills in MERN stack

Backend :
1. Type 1 : auth wala and related routes
1. Authentication routes ( kind of one time )
• Register
• Login
• Forget password
• Update pro le

2. Authorisation routes ( middleware before any other


route )
• User ( require sign in )
• Admin ( is admin )

3. Related route which req. authorisation before


• Get all user
• Get all orders
• Get order wrt speci c user
• Update order status

2. Type 2 : category routes


• Create category
• Delete category
• Update category
• Get all category
• Get single category

3. Type 3 : product related routes


1. Brain tree routes
fi
fi
fi
• Gate way
• Token generation
• Complete payment controller

2. Product normal
• Create
• delete
• Get all product
• Get single product
• Update product

3. Product additional features


• Product photo
• Product category ( for all similar product )
• Product count ( for pagination )
• Product list ( based on page no. so that particular page product will come this was
done for pagination but I did’t do the normal pagination rather use load more button )

4. Advance features product


• Search bar using regex
• Similar product using category id.
• Filter product
• Payments

Frontend :
( things are not in the same order as in the backend but ya here I have made some order follow
this don’t see code directly )
( just for clari cation I have both used bootstrap classes and normal css here )

1. Authentication
• Register
• Login
• Forgot password

2. Extra pages
• About us
• Policy
• Contact us
• Page not found

3. Search ( all things are at di erent places )


• Search context hook ( learn context rst -> its simple a use state only )
• Retrieve the word written in search and bring the project result from backend
• search.js -> now display the result of search

4. Major pages
fi
fi
ff
1. Home page
• Filter is implemented here
• Pagination + load more
• Product card array to display all product

2. Product detail
( this is the main product page which will open when you click any product in main page )

• Product description page


• Below it similar product codes
( about this one -> here you can see how front end and backend routes are used simultaneously
like the backend route is used to get image of the product and frontend route is used to open that
product where more details is clicked on similar product card . Like the point is inside the
controlled both kind of routes are used )
In this one more imp this is used the params which is used to access id or slug from the url so
here you can do rst a GPT search how this pid or slug is put in the url
Let me explain this see we use link tag for this rst time when we make link for this thing like
either on the nav bar or say on the home page like when we were making the product card to
display there on the get more details we made a link na so there in that link using all product route
we just passed this id in the link tag and when use rst click there that id gets stored in the url and
can be accessed open nav bar code for category id and open homepage code for product id and
slug

3. Category page
• simple category use state and display via loop
( there is a hook folder where this use state hook is present nothing imp its just like
a simple function written above )

4. Category product
(exactly same as product page)

• Usage of slug from category where it is rst time clicked ( nav bar link )
• Display all product of that category

5. Cart page
• Context -> auth and cart both used here
• Total price calculation using cart context ( for each person )
• Remove cart in product
• Payment complete code
• Extra : address change code is also written here but leave this

6. Layout
• Navbar
• Footer
• Admin menu
• User menu

( these menu are those dashboard left side link like what I have done is in layout I have
enterer all kind of initial links )
fi
fi
fi
fi
7 . User and admin wrapper
• Adminroute.js
• private.js

( these are used for authorisation and here we have the best use of use e ect which is also
connected to why we made auth as context so that anytime we can access the token in auth and
based on that we can make changes)
( now under this there are multiple nested routes which can only be accessed if this these wrapper
proceeds so here nesting of routes becomes very imp )

8. Nested routes -> user


• User -> pro le dashboard wali cheez simple info and one image
• User/order -> all the orders of user (this is important page)
• User/pro le -> this is used to update the user pro le details

9. Nested routes -> admin


• Admin menu -> dashboard same as prev
• Admin orders -> all orders
• Create category
• Create product
• Products
• Update products details
• Users
fi
fi
fi
ff
Ecommerce Project Related Questions :
From rst point :
Q: What is JWT, and how does it ensure secure authentication?

• JWT (JSON Web Token) is a compact, self-contained token used to securely transmit
information between a client and a server.
• Explain the structure: header, payload, and signature.
• header has 2 things first is type of token and second is hashing algo used to encrypt it,
hashing algos -> HMAC-SHA256 or RSA
• Payload has user information name, email etc
• To create the signature, you take the encoded header, the encoded payload, a secret key,
and the algorithm specified in the header. The signature ensures that the token hasn’t been
altered.
• The token is signed using a secret key (HMAC) or a public/private key pair (RSA).
• SHA-256 is a cryptographic hash function that outputs a fixed 256-bit hash.
• HMAC is a way to use hash functions (like SHA-256) along with a secret key to verify the
data's integrity and authenticity.
• HMAC : In this method, the same secret key is used to both sign and verify the token.
• RSA (Public/Private Key Pair) : The server uses a private key to sign the token and a
public key to verify it means only the person having private key can sign the token but
public key wale can verify it.
• HMAC is simpler and faster. It’s suitable when only one server is verifying the token. RSA
is useful when you want to share the public key widely without risking the private key.
• Describe how you generate a token upon successful login, send it to the client, and verify it
on every request for protected routes. ( ye to simple flow hai apan samjha denge .. khani
bna ke )
• Discuss how you handle token expiration and what steps are taken to refresh tokens.
• Like JWT token expires after certain time then user can’t verify it and he/she has to login
again .. to avoid this we can use refresh tokens
• When the user successfully logs in (providing valid credentials), the authentication server
generates two token
• An access token: Used to access protected resources (usually has a short lifespan, like
15 minutes to 1 hour).
• A refresh token: Used to obtain a new access token when the current one expires (usually
has a longer lifespan, like days or weeks).

Q : other alternatives to JWT ?


Ans :
1. Ek to session storage krke hota hai jisme : server pe aap user ke current session ka info
session id ki form me cookies me store kr lete ho
2. Google auth : authenticate users via their Google accounts, The app redirects users to
Google’s login page.
adv is Eliminates the need for custom user authentication , Users don’t need to remember
separate credentials.

*With JWT u can handle token management and authentication yourself and its simple to use aur
its stateless behavior is key why I used it.

Q : difference between authentication and authorization ?


Ans :
1. Veri es the identity of the user or system (i.e., "Who are you?”).
2. Determines the permissions and access levels of the authenticated user (i.e., "What can you do?”)
1. To con rm that the user is who they claim to be.
2. To de ne and enforce what resources or actions the user is allowed to access or perform.
1. Typically involves credentials like username/password, biometrics, or tokens.
2. Involves role-based or policy-based permissions and access controls.
fi
fi
fi
fi
Q : How did you implement password encryption, and why did you choose bcrypt over
other algorithms?

• Explain both bcrypt.hash and bcrypt.compare using code


• Why to choose bcrypt
• Bcrypt automatically adds a salt to the password before hashing. A salt is a random value
that makes the hash unique, even if two users have the same password
• Other algorithms like SHA-256 don’t include salting by default, which means you have to
handle it manually.
• Bcrypt is intentionally slow, which means it takes time to compute each hash. This makes it
much harder for attackers to guess passwords using brute-force attacks. Algorithms like
MD5 or SHA-256 are faster, making them vulnerable to brute-force attacks.

From second point :


Q : How did you implement role-based access control (RBAC) for customer and staff
dashboards? How did you separate customer and staff functionalities?
• First explain how roles are assigned .. 0/1 at database
• Describe how you used middleware or route guards to check the user's role before allowing
access to certain routes ( like pura flow code wali pdf se )
• Describe how you structured your code to handle different user roles. For example,
different routes or API endpoints for customer and staff actions.
• You can explain how you used conditional rendering on the frontend to display components
based on the user's role.
• Mention any use of state management (like Redux) to maintain user role information across
the application. ( mere case it is done using auth context hook)
• There is nothing much to write here , everything is there in the code so use that to explain
the flow

From point 3 :
Filtering :

Q : How did you implement ltering by price and category in your project? -> full ow
Q : How did you optimize performance for ltering with large datasets?
or
Q : How did you handle large datasets during ltering
Ans : wohi intern wale soln -> querying using .limit(), pagination , database me price and category
pe indexing
Q : what if a product belong to mutiple category or say multiple category selected then how
ltering will work ?
Ans : abhi to ye sab nhi socha tha ek hi click hogi category aise hi radio button rakhi hai ..
But simple hai mongodb me category ko univalue ki jagah multivalue array bna do aur ja category
box check ho to multiple values ek array me api se bhejo aur backend pe phele jaise ham
args.category=checked kr rhe the ab args.category = { $in: checked }; use kr lo baki lte and gte
same

Search :

• Explain the code flow for each of them


• For searching we have used simple Regex on name and description so they may ask what
u will do for larger dataset and why didn't u use elastic search
• U can first answer like : Initially, the project’s scale was manageable, and using regex-
based search was sufficient to meet the requirements. It was simpler to implement and did
not add external dependencies, which kept the system lightweight. Elasticsearch is a more
complex tool.
fi
fi
fi
fi
fl
• Now for larger dataset u can ans like :
• One of the easiest ways to improve search performance in a relational database is to
create indexes
• Implement caching mechanisms to store frequent search queries and results
• For very large dataset u can also explain Sharding & Partitioning
• Use elastic search
• Firstly it divides the data into three things :
◦ Indexes : Think of an index as a collection of related data. For example, you can
have an index for all your products or one for all your blog posts.
◦ Document : A document is a single record inside an index written in JSON format.
◦ Shard : When you have a lot of data, Elasticsearch splits it into smaller pieces
called shards. This helps in managing and searching data faster.
• How it works :
◦ When you add data to Elasticsearch, it analyzes the text (breaks it down into
words) and creates an inverted index.
◦ When you type in a search query, Elasticsearch quickly checks the inverted index
to find relevant documents. And also rank these documents based on relevancy
◦ Think of it as a super-fast librarian that always knows where to find exactly what
you’re looking for, even in a giant library.
◦ It is scalable and fast and can do smart searching means can handle wrong spelling
and autocomplete etc

• Product search : they can also ask why didn't u applied ML here or how u can do it using
ML
• This technique focuses on recommending products that are similar to the ones a user has
interacted with (e.g., viewed, added to cart, purchased). You can use product attributes
like category, price, brand, description, etc., to find similarities.

How It Works:
• Feature Extraction: Extract important features from products, such as keywords from the
description, product categories, price ranges, and other metadata.
• Vectorization: Convert these features into vectors using techniques like TF-IDF for text
data or word embeddings (e.g., Word2Vec or BERT).
• Similarity Measure: Use cosine similarity or Euclidean distance to measure the
similarity between products.
• Recommendation: When a user views a product, recommend other products with the
highest similarity scores.

Q : How did you handle scenarios where no search results were found? -> code me dekh lena
Q : what if after search I wan’t to put ltering ab dono kaise handle kroge ?
Ans : inside model. nd({ }) u put any object and make use $and $or $lte $gte $in $notin $eq
ef ciently to ans such question.
Q : what if I write wrong spelling then simple regex will fail ?? How to solve that ??
Ans : phele to say I was making a simple project so did’nt go for advance method used simple
regex Then say I can use Fuzzy matching : its a technique to nd similar words (how)?=> it
calculated the similarity score which is de ned as the min addition or replacement to make the
original word.
For eg. -> boook -> 1 deletion , back -> 2 replacement to make book so using like this it search
Atlas have this implementation of fuzzy matching also elastic search work on same thing and LIKE
in sql came from fuzzy searching
Further u can explain about ML and NLP

Q : What is debouncing and throatling ?

Debouncing is a technique used to control the rate at which a function is executed. It ensures that
the function is only triggered once after a speci ed delay, regardless of how many times it is called
fi
fi
fi
fi
fi
fi
within that period. It is used with search bar because a user types multiple time in the search bar and
keep deleting so multiple api request in short period this causes bashad …

How it works :
The debounce function delays the execution of the search query until the user has stopped typing for
a speci c duration (e.g., 300ms). If the user types again before the delay ends, the timer is reset. The
search query is only executed after the delay ends and no further input occurs.
( this will create a bad user experience but it is necessary to balance load in large dataset … like ek
tradeoff hai performace and experience ka )

Throttling is a technique that ensures a function is executed at regular intervals (e.g., every 200ms)
regardless of how frequently it is called. Unlike debouncing, throttling doesn't wait for the user to
stop typing completely. Like user is typing then also the query is triggered if the interval time is
ended …

Throttling is not good for search bars it is good with say in nite scroll like reels etc , because there
u wan’t to make api calls regularly not on the user interaction.

Q : Why MongoDB (a NoSQL database) instead of SQL databases?


Ans :

1. Mongo db has exible schema : MongoDB uses a document-oriented data model means it
allows to store things in form of json data , ab iss exibility ka matlab kya hai ->> means tum
ek product ki sari information like category , price , other attributes sab ek hi jagah store kr skte
where in sql due to rigid schema tumhe multiple tables bnani padti now to combine data tumhe
complex joins use krne padte …
2. Second things is again realated to schema itself : in mongo db lets say while de ning schema u
made 3 things for a product but when adding a product a new feature/attribute say colour came
so in mongo db u can directly add this here and these type of usecases are common in ecom.
3. Scalability : MongoDB is horizontally scalable, meaning it can handle large datasets by
distributing data across multiple servers. Does this means SQL is not scalable ?? Ans : no it is
also scalable but
1. SQL databases like MySQL and PostgreSQL are traditionally optimized for vertical scaling,
meaning you improve performance by adding more resources (CPU, RAM, or storage) to a
single server.
2. We can explain this in other way like : SQL databases can scale horizontally, but it’s
complex because of their relational nature
3. Data in SQL databases is often highly interrelated (using JOINs across tables). Distributing
related data across multiple servers (shards) while maintaining the integrity of relationships
can be tricky.
4. Either u need to implement manual sharding
4. Querying in mongodb is easy and intuitive than the complex join in sql .

What is REST api ??


Ans :
1. Api means creating web services that allow communication between a client and a server over
HTTP
2. REST (Representational State Transfer) is a design style (or architectural pattern) for building
APIs
fi
fl
fl
fi
fi
Key principles of REST include:
• Stateless Communication : each request from the client contains all the required information for
processing it but server do not store this state/info about the client. (Stateless)
• Resource-Oriented Design: Everything in the API is considered a "resource" (e.g., products,
users, orders), and each resource is accessed using a unique URL (endpoint).
• HTTP Methods: RESTful APIs use standard HTTP methods to perform actions on resources:
• GET: Fetch data (e.g., get product details).
• POST: Create new data (e.g., add a new product).
• PUT: Update existing data (e.g., update product details).
• DELETE: Remove data (e.g., delete a product).
• Uniform Interface: A consistent way of interacting with resources, often returning data in
formats like JSON or XML.
• Stateless URLs: Resource URLs are consistent and intuitive (e.g., /products, /users/
123/orders).

How are my api restful ?


I have used these design principle while writing api , like usage of /products , /users etc ,
Eg. used /product with get to get a product and same /product with post to add a new product
implemented standard HTTP methods (post ,put,get,delete) for operations like adding, fetching,
updating, or deleting data

Ya phir u can say : I designed APIs that allow the frontend to interact with the backend for tasks
like product ltering, cart management, and order placement. While I might not have explicitly
focused on making them RESTful, they align closely with REST principles such as statelessness,
resource orientation, and using HTTP methods appropriately.

Advantages of REST api :


1. Scalability -> statelessness ki wajah se harr request ke pass apni puri info hoti jiski wajah se
multiple request ek ek krke server handle kr skta … bina kuch store krke load badhae
2. REST is based on standard HTTP methods (GET, POST, PUT, DELETE)
3. Statelessness samjha do -> again same thing sab uske pass hai server pe kuch storing ka issue
nhi
4. Caching , rest can leaverage caching -> improving performace by reducing server load
5. Human readable urls

Disadvantages of REST api :


1. Some times statefullness is a problem also lets say I m making payment so every api call I have
to carry this sensitive and imp. Data so chances of data leaking and curruption increases
2. REST api don’t work ef cient with apps which uses Real time communication there api’s like
websocket works better
3. It also has overfetching and underfetching -> overfetching means providing unecessay and
extra data and underfetching means providing less data so we need multiple api calls

Alternatives to REST API Design :


1. GraphQL : A query language for APIs, allowing clients to request only the data they need, so it
solves the problem of overfetching and underfetching. ( used when minimizing payload size is
critical)
2. WebSockets
fi
fi
3. SOAP : A protocol using XML for exchanging structured information it has strong standards
and used for secure transaction application

Similar Product Recommendations


( kaise implement kiya bs usi pe prepare kr lo )

Payment gateway :
Q : How did you implement Braintree in your MERN stack project?

1. Braintree has provided us with Braintree SDK ( software developement kit ) which is a library
provided by Braintree to simplify integration with payment gateway , It includes prebuilt
functions and utilities for handling common payment operations like generating client tokens,
creating transactions, and managing refunds means point is sdk sab kr hi rha na

Kaise hota hai process samjhata hun ( code ydd mt krna bss process dekh lo )

Step 1: sabse phele backend ( server side ) pe client token bnta hai , ye one-time hota hai ek baar
payment ke liye
Braintree ki api se hi magte hain ye token

Code :
const braintree = require("braintree");

const gateway = new braintree.BraintreeGateway({


environment: braintree.Environment.Sandbox, // Use Sandbox for testing
merchantId: "YOUR_MERCHANT_ID",
publicKey: "YOUR_PUBLIC_KEY",
privateKey: "YOUR_PRIVATE_KEY",
});

app.get("/generate-client-token", async (req, res) => {


try {
const response = await gateway.clientToken.generate({});
res.json({ clientToken: response.clientToken });
} catch (error) {
console.error("Error generating client token:", error);
res.status(500).send("Unable to generate client token");
}
});

Step 2: ab ye one time token frontend ko bheja jata hai wo issi se wo payment page jo drop-in-ui
hai wo bna deta hai

Step 3 : ab ek drop-in-ui bn gya ab user isme details dalta hai and submit dabata hai to ab hm ek on
submit eventlistner likhte hain submit button pe jo ek nonce generate krega and this nonce is sent to
backend for further processing of payment
Step 4 : now the nonce recieved is send to Braintree server and wha se msg aata hai result.success
and payment.id ata hai jisse hm payement cnf krte
Step 5 : ab may be payment store krna ho ya order status update krna ho ..

Q : How did you handle errors during payment processing?


Ans : iska wohi answer hai yrr … hrr ques ke liye same cheez hi krni hai kuch fancy nhi
Server side : using try - catch block
Client side : jo bhi Braintree api ka message aya uske hisab se conditional error msg display on site

* Braintree me testing unke hi sandbox environment me hoti hai

Q : Can you explain the role of payment method nonces in Braintree?


Ans : A payment method nonce is a one-time-use token generated by the Braintree SDK on the
client side. It represents the user's payment details securely. The nonce is sent to the backend for
processing the transaction, ensuring sensitive information like card details are never directly
exposed to or stored by the server.

Q :What are the advantages of using Braintree compared to other payment gateways?
Ans : Braintree offers seamless integration for multiple payment methods like PayPal and cards in
one SDK. Its advanced features, such as built-in tokenization, PCI compliance, and webhook
support, make it developer-friendly and secure. Additionally, its sandbox environment and robust
documentation simplify testing and debugging.

What is this PCI compliance :


PCI compliance : it is PCI DSS -> payment card industry data security standards means they set
certain rules which ensure that companies processing, storing, or transmitting credit card
information maintain a secure environment
How Braintree ensure PCI compliance :
Tokenization -> Braintree replaces sensitive card information with a unique token (payment method
nonce) that cannot be reverse-engineered. This means sensitive data never touches your server.
Second point is Braintree handles all these tokenization by themselve means developer need not to
write anything out of it like complex encryption process etc .

Webhooks :
They are automated noti cations sent from one system to another via HTTP when speci c events
occur.
I have not used it but ye ek functionlaity hai Braintree ki
Fayda kya hai webhooks ka : lets say badi company hai to bhot Sara data hoga bhot sari payment
hogi so ek term hoti repeated polling krke means aap baar baar api request bhej rhe ho to check the
payment update but webhook me kya hai .. automated noti cations sent by Braintree to your server
when speci c events occur

So agar interviewer puche ki kaise isse scale kr skte to webhook bta dena ek acha idea hai …
fi
fi
fi
fi
Frontend :
1. Authentication

• 3 main pages register , login , forgot password


• in all pages majorly 3 hooks are used useState , useE ect, useContext
• Any time u want to make any variable in react u never use let a , u just use usestate hook

Register :

• We will take all 6 elds name email pass address answer phone-no. Which we have to sent to
backend as usestate and then simple creating of form and make a submit handler
• For every form e.preventDefault()
• Then same async arrow function and try catch block this format will remain same
• Now using axios with await to send the data and get response in res variable
• Now here I am using toast to show the message came from backend but leave that one more
thing is we are using navigate now to go to login page

Note : in the return react code rstly we have used a helper called layout this layout is just
handling those meta tags for seo so leave this

Note : for creating form simple top div then form tag then inside it take input tags and h3 tags for
their values , inside input tag main things are type , value , onchange , classname , placeholder
and required .
In type we put “text" and in case of email and password we put “email” and “password” as type
only there are multiple other types like number , checkbox, radio ,date etc

then in value we put that variable (usestate wala ) in onchange we put usestate function
Eg. onchange{(e)=>setName(e.target.value)}

Then in classname css class, placeholder what default is written in input tag eg. enter your name
then required.

Note 1 : when ever any kind of data comes from backend it is accessed into the frontend using
res.data then u type your speci c thing res.data.message, res.data.user what ever is sent from
backend

Note 2 : there is one more way to do it you can destructure the data from the res coming from
backend

Eg :> const { data } = await axios.get(`${serverval}api/v1/product`);

Login :
• form with just email and password and two button one is forgot password and login
• 2 usestate name and email and auth context hook
• Now again submit handler which will do axios and if we res.data.sucess we will do our setauth
operation
• For all this we need to understand the context hooks rst .. basically they are just usestate only
but declared kind of globally
• Now in auth context is a object with two keys user and token
• From axios we got both user and token value so we will setauth with these updated values
• One note here is our user will always remain login in our case and when new user login old user
token will get replaced into this auth
fi
fi
fi
fi
ff
• Also here we are using local storage for storing token not the cookies or something simple js
code get item set item from local storage
• Navigate and location thing is there but just learn I am navigating to “/“

Context Hooks
Note : rst open these pages -> auth context , search context , cart context to see how context is
written then open index.js to see how the prop drilling happens also login page so that u can
understand the linking between auth context and its usage

How a context hook is created ?

1. Step 1 : create context

import { createContext } from 'react';


const AuthContext = createContext();

2. Step 2 : create context provider

const AuthProvider = ({ children }) => {


const [auth, setAuth] = useState({ user: null, token: '' });

return (
<AuthContext.Provider value={[auth, setAuth]}>
{children}
</AuthContext.Provider>
);
};

Simply we put some state variable in a provider function and then return it while passing state and
its function to the children’s
And these children are parameters passed to it
Now one thing is important here in my project I have put a use e ect also with empty dependency
array which will re render and help in persisting the user login ( I will explain it Aage ).

3. Step 3 : creation of custom hook ( this is optional but a good practice )

See custom hook is not only for context it can be thought of as any reusable piece of code eg.
say u are handling a form data into multiple state hooks and when button presses u have written a
submit handler to update these state values now all this u can bundle into a say useForm hook
and export this as a custom hook

Custom hook code : const useAuth = () => useContext(AuthContext);

Now useAuth is your custom hook which u can import on any page.

4 Step 4 : wrapping into provider so that prop drilling can takes place

In my case I have done this in index.js so that complete App is wrapped into the wrapper
But it is not necessary like we can wrap speci c pages also where we want to change our auth
value this enhance the privacy and security.
The children in the auth provider is parameter to it which in our case is App itself

Multiple context hooks in our project : ( all have same format of code )
fi
fi
ff
1. Auth context : this has two things user object ( initially null ) and token ( initially empty string )
and then it is using useE ect and fetching data from local storage and storing.
2. Cart context : it have just cart variable (initially empty array) and a use e ect hook which is
again fetching data of cart from local storage like cart don’t get refreshed after reload (same
thing as above )
3. Search context : it has two things keyword (empty string ) and results (empty array) and this
thing is not fetched from local storage means that useE ect and reload persistence is not here

How everything is working ?


Note1 : we are also setting here default axios header … this I have already explained during
backend why it is imp and what this header do

When u see the login page u will see that there is a setting of auth hook like I am setting the token
there but in the auth context also there is a use e ect hook which is doing the same thing but it is
like taking data from local storage and then setting it to our state .. what is this ?
So this helps in persisting the user when he refreshes the page or closes the browser.
See rstly he will see the login page and enter his credentials and hit submit now the submit
handler at login page is called and it will ask the token and user object from backend as we have
seen then it will store all this into local storage into a “auth” variable which is handling that
multiple user can’t come at the same time thing because key for all is same. Then setting these
values to a custom hook which is our context came from prop drilling from main to app to this
page. Now this is the rst time
Now lets say user have reloaded the page and as we know as reload happens the complete thing
re renders rstly the auth provider will re render then search provider then cart provider and then
App so when this happen my useE ect inside auth context will also run once as there is nothing
in its dependency array and at this time in my local storage res.data is stored and this useE ect is
restoring that from local storage to auth hook.

Forget password:
• Simple three states email, new password and answer and then sending them to backend and
using res.data.sucess just using toast to show message and navigating to login page
• Rest same page as register.

2. Extra pages
• About us
• Policy
• Contact us
• Page not found

Direct return statement nothing else with css classes and direct css
Col-md-6 all these classname based css is part of bootstrap

3. Search
• This is divided into three parts in project search context , search input .js and search .js
• Context is already done
• Search input .js is the main page where search bar is made and we have imported search
context hook here with state as value now as we have seen this search context hook has two
things one is keyword string and second is results array.
• Now on change of search input box I have done this
• onChange={(e) => setValues({ ...values, keyword: e.target.value })}
• Means using spread operator on values means what ever is there just copy and then change
keyword to e.target.value
fi
fi
fi
ff
ff
ff
ff
ff
ff
• Now there is a button near to search bar which is submit button now on click of it we need to
make a submit handler
• Inside this submit handler we are fetching data from api where we will pass our value.keyword
in the url so that it can be accessed using params
• Then it will return array of all products
• Now again spread and updating just to values array no change stop keyword
• Then navigate to /search route which is the next page search.js
const { data } = await axios.get(
`${serverval}api/v1/product/search/${values.keyword}`
);
setValues({ ...values, results: data });
navigate(“/search”);

Note : here we passed the keyword into url using the context (most asked doubt in backend)

Search.js :
• We have been navigated from search input to here as soon as we clicked the search button
• Now here we will use both type of context search and cart
• See the usage of cart is imp .. we have our product cards now we will have a add to cart button
and then on click of it we will update the cart using spread operator and new product also this
will be added to local storage as we have seen our cart items are stored in local storage.
• We can do all this onclick function thing in a separate handler but whi kri diya
• Here there is no logic just react code
• See the usage of ternary operator in return code
• Using values.result.map we are looping over all product and displaying them
• This is similar to what we will do in the main page to display products like do a loop then open
a div rstly put img tag then other h and p tags to display name and description and then a add
to cart and more details button
• There is also one more thing inside more details onclick I am navigating it to product
description page along with p.slug value which could also be p._id . (Imp)

Note : what is kept in the img tag src … so here we are using get photo api and calling our image
by sending p._id

Here two imp things to notice :


While writing backend I was thinking how something will be stored into backend url
1. Here in img we are sending p._id because we are looping on all products present in our
value.result array so we have all info about product
2. Say if we are displaying products on the main page there also we are using get all product api
rst while will store all product object into array and while looping we know the exact product
which we are talking about and can send its p._id to get photo api or say more details api .
3. Then while asking for search result also we sent value.keyword as params using search
context.

4. Home Page

5. Product detail
• This page contains the main product display and similar product code
• See till now we have seen at backend we can access id from url using req.params and that id is
sent from frontend
fi
fi
• But frontend also have their own url which we de ne at the routes so we can have some id or
slug into these url also and those can be accessed using useparams hook.
• How these params are set into url ? -> see we have displayed products using loop on the main
page so while displaying I know everything about product and as I click on more details button
their so at this time I have product id or slug so which I can pass to this page url and now on
this page I can access this using params , one more eg. is you have multiple category
displayed on nav bar and when u click on the speci c category now think your self how did u
displayed these multiple category name -> manually to nhi likh diya hoga as a good developer
u have asked for all category from backend in a state array and at this time u have all the
information of all category in this array including its id or slug so on click of this category u can
redirect it to some page and pass this id or slug into it url and now on that page u can use this
id or slug to get the exact category value …. Just look at it how good it is
• Now on this page I have few things one is particular product and second is similar product
• So for particular product I just need a object kind of state to store all its details price desc name
etc and for similar product I need a empty state array also when these products are here so
think your self u will also have a add to cart button so ofc u need a cart state (context wala) . So
we have 3 states and 1 use param hook at the top this use param comes similar to other hooks
using react-router-dom
• Now here we have nothing to click as it was in login and register .. so we will use useE ect
hook to use our handler
• 2 handlers we have to get the complete details of this single product and get similar products
• First one requires slug at backend and that slug we will get from param and update this into
product object and simultaneously call similar product function by sending product._id and
product.cateogory._id as parameter here we don’t need any params here because complete
product details I have
• Now similar product handler : simply we have pid and cid call the api and it will give array of
products set them to second similar product state array
• Now display the main product details and everything and here just we have add to cart option
• Again image is done using get photo api by sending the p._id
• Then show similar product use ternary operator on similar product array length and display
them in a loop this code is exactly copied form main page code simple for every add to cart
onclick just update context cart along with spread operator and for every more details onclick
just navigate to this page only and change the slug value in the url
• Note : while displaying currency we get p.price then we have to convert that to Locale string
then choose style as currency and currency as INR to display no. in that formal

Note :
fi
fi
ff

You might also like