import all components after we use them in routing
<nav><Linkto={'/'}><button>Home</button></Link></nav>// Also Use NavLink insted of Link
=> Create Some Pages using Bootstrap 5
=> Context API (IMP) Learn
create a useContext => createContext
provider
consumer => useContext Hook
// => ProductContext.jsximport{createContext,useContext}from"react";constAppContext=createContext();constAppProvider=({children})=>{return(<AppContext.Providervalue={{myname:"Jay Patel"}}>{children}</AppContext.Provider>);};constuseProductContext=()=>{returnuseContext(AppContext);}export{AppContext,AppProvider,useProductContext}// => App.js<AppProvider>...</AppProvider>// wrap all Componenet wit <AppProvider> also import them// => use at Any Component Pageimport{useProductContext}from'../Context/ProductContext'const{myname}=useProductContext()// Recive data here component na andar use karvu
// Fetching API data uisng Axios constgetProducts=async(url)=>{constresponse=awaitaxios.get(url);constProducts=awaitresponse.data;console.log(Products)}// Call functionuseEffect(()=>{getProducts(API);},[])// if [] not use then useeffect run inifnity time
=> State Managemnet (useReducer)
=> why use => alredy axios thi api to avi gay pan vare vare use karva ya filter karva ene call na karva pade atle apde ene ek jagiye stor kari des and pasi tya thi use karsu fillter kari kari ne
const[state,dispatch]=useReducer(reducer,initialState)// State => Update Output Data// dispatch => Functionality add here// reducer => functionality import from other file// initialState => initialState of data
main useReducer ma thay m ke e condication chake kare and jo conditionmatcch they to tema je code rey te paraman initialState state na data ne chnage kare
dispatch({type:"Set_Loading"});dispatch({type:"My_API_Data",payload:Products});dispatch({type:"My_Error"});// also we use try and catch for error handling // => productsReducer.jsxconstProductReducer=(state,action)=>{// initialState ={// isLoading:false,// isError:false,// products:[],// fearureProducts:[] }// check all action and action mujar case run thay and je fillter joye te paramne output mate code lakhvoswitch(action.type){case"Set_Loading":
return{
...state,isLoading:true};case"Set_API_Data":
constfearureData=action.payload.filter((e)=>{returne.fearured===true;})return{
...state,isLoading:false,products:action.payload,fearureProducts:fearureData};default:
returnstate}returnstate}exportdefaultProductReducer
=> Passing Data In URL
<Routepath='/ProductDetailPage/:id'Component={ProductDetailPage}></Route>//App.js<Linkto={`/ProductDetailPage/${id}`}><button>View</button></Link> //Where click function use also where id is available// acces id const{id}=useParams();
=>Use Perems (get data from url) Product detail Page
create api uisng reducer for single product
// Single Product Context => ProductContext.jsx// function pass is AppProviderconstsingleProduct=async(url)=>{constresponse=awaitaxios.get(url);constSingleProducts=awaitresponse.data;console.log("SingleProducts",SingleProducts)dispatch({type:"Single_Produsct",payload:SingleProducts})}// Get Single Product Fuction uisng Context APIlet{singleProduct}=useProductContext()// In Product Detail Page ,we use use Params for geting URL id // Use singleProduct function in useEffect Hook and pass url for single productconst{id}=useParams();
chnage reducer and contect datas
pass the single data
// => ProductReducer.jsxcase"Single_Set_API_Data":
return{ ...state,singleproductdata:action.payload};// Use any where you wantconst{singleProduct, singleproductdata}=useProductContext()
=> Cart + or - System
use state hook
const[amount,setAmount]=useState(1);// create 2 function one increment or one for decrement functionsetIncrement(){amount>1?setAmount(amount+1):setAmount(1)}functionsetDecrement(){amount>1?setAmount(amount-1):setAmount(1)}// : => OR// ? => Not
=> Reduce use to chnage component
use Reducer
context ni adar j reducer use karvu
adding some variables in initialSate and chnage using Reducer
geting data with context api and chack varibale with if else ,if true then display that other wise else part code
create Context and create some variables in initialSate
in reducer file check falanu and dheknu and run code usring them
constProductReducer=(state,action)=>{switch(action.type){case"falanu":
return{message:"This Is Falanu"};case"dheknu":
return{message:"This Is Dheknu"};// Both Case are false then run default case default:
returnstate}}exportdefaultProductReducer
in componet get message using context and check them using if and else if falanu them component1 else component2
'
=> Filter Product
use Reducer for filler data / contect API to geting Data
all fillter function create in contex file and call from diffrent components
use simple logic and code in reducer file where trigger by contex dispatch()
get each input/button name or value using dom event method
// initialState => Default values constinitialState={filter_products: [],all_products: [],grid_view: true,sorting_value: "lowest",filters: {text: "",category: "all",company: "all",color: "all",maxPrice: 0,price: 0,minPrice: 0,},};// Contect pageconst[state,dispatch]=useReducer(reducer,initialState);// call reducer// to sort the productuseEffect(()=>{dispatch({type: "FILTER_PRODUCTS"});dispatch({type: "SORTING_PRODUCTS"});},[products,state.sorting_value,state.filters]);// geting data from context api// Reducer pagecase"FILTER_PRODUCTS":
let{ all_products }=state;lettempFilterProduct=[...all_products];const{ text, category, company, color, price }=state.filters;if(text){tempFilterProduct=tempFilterProduct.filter((curElem)=>{returncurElem.name.toLowerCase().includes(text);});}if(category!=="all"){tempFilterProduct=tempFilterProduct.filter((curElem)=>curElem.category===category);}if(company!=="all"){tempFilterProduct=tempFilterProduct.filter((curElem)=>curElem.company.toLowerCase()===company.toLowerCase());}if(color!=="all"){tempFilterProduct=tempFilterProduct.filter((curElem)=>curElem.colors.includes(color));}return{
...state,filter_products: tempFilterProduct,};// Simple mean all chnage set with initialState case"CLEAR_FILTERS":
return{
...state,filters: {
...state.filters,text: "",category: "all",company: "all",color: "all",maxPrice: 0,price: state.filters.maxPrice,minPrice: state.filters.maxPrice,},};
=> Adding Into Cart
add link with id to go cart page
<Linkto={'/cart'}onClick=(()=>addToCart(id,amount,product))>AddToCart</Link> //add in product detail page // ahiya click karsu to context ma addToCart run thase// create addtoCart function
when we click on btn then we need some datas of this product => id , total amount, contity,product details
create cartContext page and cartReducer page
// => Cart ContextpageinitialSate={cart:[]}// create cartContext page and create contextconst[state,dispatch]=useReducer(reducer,initialSate)constaddToCart=(id,color,amount,product)=>{dispatch({type: "ADD_TO_CART",payload: { id, color, amount, product }});};// pass addToCart into Provider jethi cart component m click karsu to ahiya run thase // => reducer pageif(action.type=="ADD_TO_CART"){let{id,color.amount,product}=action.payload;//via payload destructureletcartProduct={
name ="flanu dheknu dekhnu "// use product.name// get all useefull data here}return{
...state,cart:[...state.cart,cartProduct]// update cart into inisitalState cart (adding item in cart)}}
=> Detele Item
when click on delete btn then run delete funtion
thet function call at context file
trigerting reducer then je id pass they e id sivay bija data display thay using => !== (filter function)
=> Loacl Storage for save Cart Data
// Use Loacal stoarge to save data in temporaryuseEffect(()=>{localStorage.setItem("UserName_Cart",JSON.stringify(state.cart))},[state.cart])
jab jab cart chnage thase tab tab useEffect run thase and localStorage ma Update thatu rese
// Get LocalStorage DataletnewCartData=localStorage.getItem("UserName_Cart")if(newCartData===[]){return[]}else{returnJSON.parse(newCartData);}// in initialState chnage cart:[] => cart:functionName()
if need to clear the cart then set => cart:[]
=> Total_Item
use Reducemethod
// jyare page cart change thay tab total chnage thay so use useEffectuseEffect(()=>{dispatch({type:"Cart_Total_Item"})})// => reduce fileif(action.type=="Cart_Total_Item"){letupdateItemVal=state.cart.reduce((initial_Element,current_Element)=>{let{amount}=current_Element;initial_Element=initial_Element+amountreturninitial_Element},0)return{
...state,total_item:updateItemVal// access and chnage initialSate Value}}
importReact,{useReducer}from'react';constMyComponent=()=>{const[state,dispatch]=useReducer(reducer,initialState);// Example usageconstincrement=()=>{dispatch({type: 'INCREMENT'});};constdecrement=()=>{dispatch({type: 'DECREMENT'});};constreset=()=>{dispatch({type: 'RESET'});};return(<div><p>Count: {state.count}</p><buttononClick={increment}>Increment</button><buttononClick={decrement}>Decrement</button><buttononClick={reset}>Reset</button></div>);};
State
importReact,{useState}from'react';constMyComponent=()=>{// Initialize state using useStateconst[count,setCount]=useState(0);const[message,setMessage]=useState('');// Update stateconstincrement=()=>{setCount(count+1);};constdecrement=()=>{setCount(count-1);};consthandleChange=(event)=>{setMessage(event.target.value);};return(<div><p>Count: {count}</p><buttononClick={increment}>Increment</button><buttononClick={decrement}>Decrement</button><br/><inputtype="text"value={message}onChange={handleChange}/><p>Message: {message}</p></div>);};exportdefaultMyComponent;
UseEffect
data ma koy chnage ave tab te run thay
bar thi ene chnage karva ni tye thay to run thY
useEffect(()=>{consol.log("run this code")},[data])// if data are chnage then run print code ``-[data]lakhvathidataparnirbhartheyjayjethidataenajunadatathichangeavetocoderunthay-[]lakhvathikhaliekvarcoderunthaynepasirukijay