Tuesday, December 13, 2022

React: UseEffect Dec

 const Login = (props) => {

  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState();
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  useEffect(()=>{
   const identifier= setTimeout(()=>{
    console.log('triggered only once for all the  keystrokes typed in between 1000millis')
    setFormIsValid(
      enteredEmail.includes('@') && enteredPassword.trim().length > 6
    );
   },1000);
   return ()=>{
    console.log("cleanup...")
    clearTimeout(identifier);
  };  //cleaning up after 5seconds
  },[enteredEmail, enteredPassword])
  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);

    // setFormIsValid( // moved to useEffect.
    //   event.target.value.includes('@') && enteredPassword.trim().length > 6
    // );
  };
const passwordChangeHandler = (event) => {
    setEnteredPassword(event.target.value);

    setFormIsValid(
      event.target.value.trim().length > 6 && enteredEmail.includes('@')
    );
  };
 const validateEmailHandler = () => {
    setEmailIsValid(enteredEmail.includes('@'));
  };

  const validatePasswordHandler = () => {
    setPasswordIsValid(enteredPassword.trim().length > 6);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(enteredEmail, enteredPassword);
  };




  <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            emailIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={enteredEmail} placeholder="UseEffect Used Here-- [Check Console]"
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${
            passwordIsValid === false ? classes.invalid : ''
          }`}
        >


FILE: LOGIN.js
import React, { useEffect, useState } from 'react';

import Card from '../UI/Card/Card';
import classes from './Login.module.css';
import Button from '../UI/Button/Button';

const Login = (props) => {
  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState();
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  useEffect(()=>{
   const identifier= setTimeout(()=>{
    console.log('triggered only once for all the  keystrokes typed in between 1000millis')
    setFormIsValid(
      enteredEmail.includes('@') && enteredPassword.trim().length > 6
    );
   },1000);
   return ()=>{
    console.log("cleanup...")
    clearTimeout(identifier);
  };  //cleaning up after 5seconds
  },[enteredEmail, enteredPassword])
  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);

    // setFormIsValid( // moved to useEffect.
    //   event.target.value.includes('@') && enteredPassword.trim().length > 6
    // );
  };

  const passwordChangeHandler = (event) => {
    setEnteredPassword(event.target.value);

    setFormIsValid(
      event.target.value.trim().length > 6 && enteredEmail.includes('@')
    );
  };

  const validateEmailHandler = () => {
    setEmailIsValid(enteredEmail.includes('@'));
  };

  const validatePasswordHandler = () => {
    setPasswordIsValid(enteredPassword.trim().length > 6);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(enteredEmail, enteredPassword);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            emailIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={enteredEmail} placeholder="UseEffect Used Here-- [Check Console]"
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${
            passwordIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            value={enteredPassword}
            onChange={passwordChangeHandler}
            onBlur={validatePasswordHandler}
          />
        </div>
        <div className={classes.actions}>
          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>
        </div>
      </form>
    </Card>
  );
};

export default Login;

Wednesday, November 30, 2022

usereducer

 import React, { useReducer, useState, useEffect } from "react";


const emailReducer = (state, action) => {
  if (action.type === "USER_INPUT") {
    return { value: action.val, isValid: action.val.length > 5 ? true : false };
  }
  if (action.type === "INPUT_BLUR") {
    return {
      value: state.value,
      isValid: state.value.length > 5 ? true : false,
    };
  }
  return { value: "", isValid: false };
};

const passwordReducer = (state, action) => {
  if (action.type === "PASS_IP") {
    return {
      value: action.value,
      isValid: action.value.length > 5 ? true : false,
    };
  } else if (action.type === "PASS_BLUR") {
    return {
      value: state.value,
      isValid: state.value.length > 5 ? true : false,
    };
  } else {
    return { value: "", isValid: null };
  }
};
const Login = () => {
  const [formIsValid, setFormIsValid] = useState(false);
  const [emailState, dispatchEmail] = useReducer(emailReducer, {
    value: "",
    isValid: null,
  });
  const [passState, dispatchpass] = useReducer(passwordReducer, {
    value: "",
    isValid: null,
  });

  //---------

  useEffect(() => {
    console.log("EFFECT RUNNING");

    return () => {
      console.log("EFFECT CLEANUP");
    };
  }, []);
  const { isValid: emailIsValid } = emailState;
  const { isValid: passwordIsValid } = passState;

  useEffect(() => {
    const identifier = setTimeout(() => {
      console.log("Checking form validity!");
      setFormIsValid(emailIsValid && passwordIsValid);
    }, 500);

    return () => {
      console.log("CLEANUP");
      clearTimeout(identifier);
    };
  }, [emailIsValid, passwordIsValid]);
  //---------------

  const emailChangeHandler = (event) => {
    dispatchEmail({ type: "USER_INPUT", val: event.target.value });
    console.log("dis em");
  };

  const validateEmailHandler = () => {
    dispatchEmail({ type: "INPUT_BLUR" });
  };

  const passwordHandler = (event) => {
    dispatchpass({ type: "PASS_IP", value: event.target.value });
  };
  const passwordBlurHandler = () => {
    dispatchpass({ type: "PASS_BLUR" });
  };
  const submitHandler = (event) => {
    event.preventDefault();
    // props.onLogin(emailState.value, enteredPassword);
  };

  return (
    <form onSubmit={submitHandler}>
      email:{emailState.isValid}
      pass:{passState.isValid}
      <div>
        {emailState.value}
        <label htmlFor="email">E-Mail</label>
        <input
          style={{ color: emailState.isValid ? "" : "red" }}
          type="email"
          id="email"
          value={emailState.value}
          onChange={emailChangeHandler}
          onBlur={validateEmailHandler}
        />
      </div>
      <input
        type="password"
        value={passState.value}
        onChange={passwordHandler}
        onBlur={passwordBlurHandler}
      />
      <button type="submit" disabled={!formIsValid}>
        submit
      </button>
    </form>
  );
};
export default Login;

Tuesday, November 29, 2022

React: usereducer

 LOGIN.js


Globally


const emailReducer = (state, action) => {

  if (action.type === 'USER_INPUT') {

    return { value: action.val, isValid: action.val.includes('@')};

  }

  if (action.type === 'INPUT_BLUR') {

    return { value: state.value, isValid: state.value.includes('@') };

  }

  return { value: '', isValid: false };

};


Inside Login Function

const [emailState, dispatchEmail] = useReducer(emailReducer, {

    value: '',

    isValid: null,

  });



const emailChangeHandler = (event) => {

    dispatchEmail({type: 'USER_INPUT', val: event.target.value});


    setFormIsValid(

      event.target.value.includes('@') && enteredPassword.trim().length > 6

    );

  };

  

    const validateEmailHandler = () => {

    dispatchEmail({type: 'INPUT_BLUR'});

  };

  

  

  

  const submitHandler = (event) => {

    event.preventDefault();

    props.onLogin(emailState.value, enteredPassword);

  };

  

  

  

  

  return (

    <Card className={classes.login}>

      <form onSubmit={submitHandler}>

        <div

          className={`${classes.control} ${

            emailState.isValid === false ? classes.invalid : ''

          }`}

        >

          <label htmlFor="email">E-Mail</label>

          <input

            type="email"

            id="email"

            value={emailState.value}

            onChange={emailChangeHandler}

            onBlur={validateEmailHandler}

          />

        </div>

Monday, November 21, 2022

IMP: Debouncing : useEffect

 


useEffect(()=>{
const identifier=setTimeout(()=>{
setFormIsValid(
enteredEmail.includes('@') && enteredPassword.trim().length>6
)
},500)
return ()=>{
console.log('Cleanup');
clearTimeout(identifier);
}
},[enteredEmail,enteredPassword])


Thursday, November 17, 2022

React: Popup modal

Add backdrop to root for click
app.js

import logo from './logo.svg';
import './App.css';
import Modal from './modal/Modal';
import { useState } from 'react';

function App() {
  const [showPop,setShowPop]=useState(false)
  const subForm=()=>{
    setShowPop(true)
  }
  return (
    <div className="App">
     <button onClick={subForm}>show</button>
    {showPop && <Modal></Modal>}
    </div>
  );
}

export default App;
-----------------------------------------------------------
Modal.js
import React, { Fragment } from "react";
import classes from './Modal.module.css';

const Modal=()=>{
return <Fragment><div className={classes.backdrop}><div className={classes.modal}>
<header className={classes.header}>
    <h2>Error</h2>
</header>
<div className={classes.content}>this is body</div>
<footer className={classes.actions}>
    okay
</footer>
</div></div></Fragment>
}
export default Modal;
----------------------------------------------------------
.backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: 10;
    background: rgba(0, 0, 0, 0.75);
  }

.modal {
    position:fixed;
    top:30vh;
    left:10%;
    width: 80%;
    overflow: hidden;
    z-index: 100;
      }
     
.header{
background-color: gray;
padding: 1rem;
}

.header h2{
    margin: 0;
    color: white;
    }

.content{
padding: 1rem;
background-color: white;
}

.actions{
padding: 1rem;
display: flex;
justify-content: flex-end;
background-color: gray;
}


@media (min-width: 768px) {// used for adjusting size
    .modal {
      left: calc(50% - 20rem);
      width: 40rem;
    }
  }

 

Tuesday, November 15, 2022

htmlFor

<label htmlFor="username"> UserName </label>
<input id="username" type="text"/>

Friday, November 4, 2022

Http show error message on success or failure







 






import React, { useState } from 'react';


import MoviesList from './components/MoviesList';
import './App.css';

function App() {
  const [movies, setMovies] = useState([]);
  const [isLoading,setIsLoading]=useState(false);
  const [error, setError]=useState(null)

  // function fetchMoviesHandler(){
  //   fetch('https://swapi.py4e.com/api/films').then(response=>{
  //     return response.json();
  //   }).then(data=>{
  //     const transformedMovies=data.results.map(movieData=>{
  //       return {
  //             id: movieData.episode_id,
  //             title: movieData.title,
  //             openingText: movieData.opening_crawl,
  //             releaseDate: movieData.release_date,
  //       }
  //     })
  //     setMovies(transformedMovies)
  //   })
  // }
 async function fetchMoviesHandler(){
  setIsLoading(true);
  setError(null)
  try{
  const response= await fetch('https://swapi.py4e.com/api/film')
 
  // const data  = await response.json();  //to show exact syntax error
  if(!response.ok){
    throw new Error('Something went wrong')  //to show defined error message
  }
  const data  = await response.json();
    const transformedMovies=data.results.map(movieData=>{
      return {
            id: movieData.episode_id,
            title: movieData.title,
            openingText: movieData.opening_crawl,
            releaseDate: movieData.release_date,
      }
    })
    setMovies(transformedMovies)
    // setIsLoading(false); moved to bottom
  }catch (error){
   setError(error.message);
  }
  setIsLoading(false);}
 
return (
  <React.Fragment>
    <section>
      <button onClick={fetchMoviesHandler}>Fetch Movies</button>
    </section>
    <section>
      {!isLoading && movies.length>0 && <MoviesList movies={movies} />}
      {!isLoading && movies.length===0 && !error && <p>No movies found</p>}
      {!isLoading && error && <p>{error}</p>}
      {isLoading && <p>Loading...</p>}
    </section>
  </React.Fragment>
);
}

export default App;

Wednesday, November 2, 2022

React: class component

 import {Component } from 'react'; //-------------added this line

import classes from './User.module.css';

class User extends Component{
  render(){
    return <li className={classes.user}>{this.props.name}</li>;
  }
}
//----------commented below and added above
//const User = (props) => {
 // return <li className={classes.user}>{props.name}</li>;
//};

export default User;

React useMemo() performance

 https://www.w3schools.com/react/react_usememo.asp






usememo memorize the value and uses it for every execution if no change is done to value, 

it compares prev state with new state, if no change found then usememoze value is used directly 

React: Usecallback & usememo--To improve performance


  

v:157: usecallback

use it when required instead of running every time. 

(instead of running all the states,or all data in function, we can control it with usecallback, triggered only when requeired, check below code, 2 buttons added first click on paragraph button tht doesnt work, when clicking on first buttong and then clik on 2nd it works and it triggers, check with console)

function App(){

const [showParagraph, setShowParagraph]=useState(false);

const [allowToggle, setAllowToggle]=useState(false);


const toggleParagraphHandler=useCallback(()=>{

if(allowToggle){

setShowParagraph((prevShowParagraph)=>!prevShowParagraph);

}

},[allowToggle]);


const allowToggleHandler=()=>{

setAllowToggle(true);

}


return <Fragment>

<Button onClick="allowToggleHandler">Allow Toggling</Button>

<Button onClick="toggleParagraphHandler">Toggle Paragraph</Button>

</Fragment>

}

Monday, October 31, 2022

React Adding styles function

   const btnClasses=`${classes.button} ${classes.bump}`;//adding styles

  return (
    <Fragment>
      <button className={btnClasses} onClick={props.onClick}>
     //initially <button className={classes.button} onClick={props.onClick}>




Sunday, October 30, 2022

React Context: use context instead of passing data with usestate to nested components

Readme


1. create Cart-Context.js with default structure (ie, **{items:[],totalAmount:0,addItem:(item)=>{},removeItem:(id)=>{}}**)

2. create CartProvider.js with above Cart-Context default obj structure,using it with dynamic values 

{ items:[],totalAmount:0, addItem:addItemToCartHandler,removeItem:removeItemFromCartHandler },

ii.Create reducer and dispatch data from functions with addItemToCartHandler, removeItemFromCartHandler

iii.create usestate and add reducer to usestate

iv.<CartContext.Provider value={cartContext}> {props.children} </CartContext.Provider>

3.In app.js <CartProvider>  <Header onShowCart={showCartHandler}/>... </CartProvider>

4.In header.js <header className={classes.header}><HeaderCartButton onClick={props.onShowCart}></HeaderCartButton></header>

5.HeaderCartButton.js :


const HeaderCartButton = (props) => {

    const cartCtx= useContext(CartContext);

    const numberOfCartItems= cartCtx.items.reduce((curNumber, item)=>{

        return curNumber+item.amount;

    },0);

  return (

    <Fragment>

      <button className={classes.button} onClick={props.onClick}>

        {/* 3. for popopening */}

        <span className={classes.icon}>

          <CartIcon/>

        </span>

        <span>Cart</span>

        <span className={classes.badge}>{numberOfCartItems}</span>

      </button>

    </Fragment>

  );

};

_________________________________________________________


Cart-Context.js

import React from "react";

const CartContext=React.createContext({
    items:[],
    totalAmount:0,
    addItem:(item)=>{},
    removeItem:(id)=>{}
});

export default CartContext


2.CartProvider.js

import { useReducer } from "react";
import CartContext  from "./cart-context";
const defaultCartState={
    items:[],
    totalAmount:0
};
const cartReducer=(state,action)=>{
    if(action.type="ADD"){
    const updatedItems= state.items.concat(action.item);
    const updatedTotalAmount=state.totalAmount+action.item.price*action.item.amount;
    return {
        items:updatedItems,
        totalAmount:updatedTotalAmount
    };
    }else if(action.type="REMOVE"){

    }
   return defaultCartState;
}
const CartProvider= props=>{
   const [cartstate, dispatchCartAction]= useReducer(cartReducer,defaultCartState);
    const addItemToCartHandler=(item)=>{
        dispatchCartAction({type:'ADD',item:item});
    }
    const removeItemFromCartHandler=(id)=>{
    dispatchCartAction({type:"REMOVE",id:id})
    }
    const cartContext={ // first add these below lines next write reducer code.
        // items:[],totalAmount:0, initially like this b4 adding reducer
        items:cartstate.items,
        totalAmount:cartstate.totalAmount,
        addItem:addItemToCartHandler,
        removeItem:removeItemFromCartHandler
    };
    return <CartContext.Provider value={cartContext}>
       {props.children}
    </CartContext.Provider>
}

export default CartProvider;

3.App.js

 return (
    <CartProvider>
      {cartIsShown && <Cart onClose={hideCartHandler}/>}
      <Header onShowCart={showCartHandler}/>
       {/* 1. for popopening */}
      <main>
        <Meals />
      </main>
    </CartProvider>
  );
}

export default App;
4.Header.js 

import React, { Fragment } from "react";
import HeaderCartButton from "./HeaderCartButton";
import classes from './Header.module.css';
import mealsImage from '../../assets/meals.jpg'
const Header = (props)=>{
    return <Fragment>
        <header className={classes.header}>
        <h1>ReactMeals</h1>
        <HeaderCartButton onClick={props.onShowCart}></HeaderCartButton>
         {/* 2. for popopening */}
        </header>
        <div className={classes['main-image']}><img src={mealsImage}></img></div>
    </Fragment>
}
export default Header;

HeaderCartButton.js
import CartContext from "../../store/cart-context";


const HeaderCartButton = (props) => {
    const cartCtx= useContext(CartContext);
    const numberOfCartItems= cartCtx.items.reduce((curNumber, item)=>{
        return curNumber+item.amount;
    },0);
  return (
    <Fragment>
      <button className={classes.button} onClick={props.onClick}>
        {/* 3. for popopening */}
        <span className={classes.icon}>
          <CartIcon/>
        </span>
        <span>Cart</span>
        <span className={classes.badge}>{numberOfCartItems}</span>
      </button>
    </Fragment>
  );
};
export default HeaderCartButton;

Saturday, October 22, 2022

React: passing data from multiple child to parent -

     In 1.app.js 1 <Header onShowCart={showCartHandler}/> Go to 2.Header Component 2 <HeaderCartButton onClick={props.onShowCart}></HeaderCartButton> Go to 3.HeaderCardButton Component 3 <button className={classes.button} onClick={props.onClick}>

App.js

Header.js
HeaderCartButton.js


Tuesday, October 18, 2022

React Input.js COmponent --CART proj

 input.js

import React, { Fragment } from "react";
import classes from './Input.module.css';

const Input=(props)=>{
    return         <div    className={classes.input}>
        <label htmlFor={props.input.id}>{props.label}</label>
        <input {...props.input} />
        </div>
}
export default Input

 {/* {label props.input.id} added as {...props.input}for inp,wit  spread oper auto added type=txt  */}
       
input.module.css
.input {
    display: flex;
    align-items: center;
    margin-bottom: 0.5rem;
  }
 
  .input label {
    font-weight: bold;
    margin-right: 1rem;
  }
 
  .input input {
    width: 3rem;
    border-radius: 5px;
    border: 1px solid #ccc;
    font: inherit;
    padding-left: 0.5rem;
  }

MealItemForm:
 <Input
          label="Amount"
          input={{
            id: "amount_"+props.id,
            type: "number",
            min: "1",
            max: "5",
            step: "1",
            defaultValue: "1",
          }}
        />
        {/* with one {} evaluate js exp, with 2 {{}} sets as obj */}




React: passing data/keys to childs


1.Available Meals:(Result data)

const AvailableMeals = () => {
  const mealsList = DUMMY_MEALS.map((meal) => <MealItem key={meal.id} name={meal.name} description={meal.description} price={meal.price}/>);
2.MealItem: (Row Data)
 <div> <MealItemForm id={props.id}></MealItemForm></div>


3.MealItemForm

const MealItemForm = (props) => {
  return (
    <Fragment>
      <form className={classes.form}>
        <Input
          label="Amount"
          input={{
            id: "amount_"+props.id,
            type: "number",
            min: "1",
            max: "5",
            step: "1",
            defaultValue: "1",
          }}
        />
        {/* with one {} evaluate js exp, with 2 {{}} sets as obj */}
        <button>+ Add</button>
      </form>
    </Fragment>
  );
};

 

Monday, October 17, 2022

React: Card.js

 Card.js

import classes from './Card.module.css';

const Card = props => {
  return <div className={classes.card}>{props.children}</div>
};

export default Card; Card.css
.card {
    padding: 1rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
    border-radius: 14px;
    background-color: white;
  }

Saturday, October 15, 2022

React: Filling user input box misses highlights that input on submit. (order top to bottom)

 129 lec

diving into forward refs

React: creating component for input- for reusable input box

 Login.js

Initially 

<div
          className={`${classes.control} ${
            emailstate.isValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={emailstate.value}
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>



Input.js
import React from "react";
import classes from './Input/Input.module.css'
const Input=(props)=>{
    return <div
    className={`${classes.control} ${
      props.isValid === false ? classes.invalid : ''
    }`}
  >
    <label htmlFor="{props.id}">{props.label}</label>
    <input
      type="{props.type}"
      id="{props.id}"
      value={props.value}
      onChange={props.onChange}
      onBlur={props.onBlur}
    />
  </div>
}

export default Input;

Login.js changed to
 <Input
          id="email"
          label="E-mail"
          type="email"
          isValid={emailIsValid}
          value={emailstate.value}
          onChange={emailChangeHandler}
          onBlur={validateEmailHandler}
        />














Friday, October 14, 2022

React :logout separate component using createcontext

auth-context.js

import React, { useState,useEffect } from "react";
const AuthContext = React.createContext({
  isLoggedIn: false,
  onLogout: () => {}, //for better ide autocompletion test in navigation <button onclick=ctx.onlogout autoretrived
  onLogin:(email,password)=>{}
});

export const AuthContextProvider = (props) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  useEffect(()=>{
    const storedLocalStorage=localStorage.getItem('isLoggedIn');
    if(storedLocalStorage==="1"){
      setIsLoggedIn(true);
    }
  },[]);
  const logoutHandler = () => {
    localStorage.removeItem('isLoggedIn');
    setIsLoggedIn(false);
  };
  const loginHandler = () => {
    localStorage.setItem('isLoggedIn','1');
    setIsLoggedIn(true);
  };
  return (
    <AuthContext.Provider
      value={{ isLoggedIn: isLoggedIn, onLogout: logoutHandler,onLogin:loginHandler }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};
// exporting both files here AuthContextProvider and AUthcontext

export default AuthContext;

Navigation:
import React, {useContext} from 'react';
import AuthContext from '../../store/auth-context';

import classes from './Navigation.module.css';

const Navigation = () => {
 const ctx=  useContext(AuthContext);  //changes: newly added this and imported useContext
  return (
    // <AuthContext.Consumer>   //Removed these 3 lines
    //   {(ctx)=>{
    //     return (
        <nav className={classes.nav}>
          <ul>
            {ctx.isLoggedIn && (
              <li>
                <a href="/">Users</a>
              </li>
            )}
            {/* {props.isLoggedIn && ( */}
            {ctx.isLoggedIn && (
              <li>
                <a href="/">Admin</a>
              </li>
            )}
            {ctx.isLoggedIn && (
              <li>
                <button onClick={ctx.onLogout}>Logout</button>
              </li>
            )}
          </ul>
        </nav>
    //     )
    //   }}  
    //   {/* will get data of auth context comp */}
   
    // </AuthContext.Consumer>
  );
};

export default Navigation;


APp.js
import React, { useContext } from 'react';

import Login from './components/Login/Login';
import Home from './components/Home/Home';
import MainHeader from './components/MainHeader/MainHeader';
 import AuthContext from './store/auth-context';

function App() {
 const ctx= useContext(AuthContext);   // added new
  //all moved to auth-context.js
//   const [isLoggedIn, setIsLoggedIn] = useState(false);

// useEffect(()=>{
//   const storedLocalStorage=localStorage.getItem('isLoggedIn');
//   if(storedLocalStorage==="1"){
//     setIsLoggedIn(true);
//   }
// },[]);
//   const loginHandler = (email, password) => {
//     // We should of course check email and password
//     // But it's just a dummy/ demo anyways
//     localStorage.removeItem('isLoggedIn');
//     localStorage.setItem('isLoggedIn','1');
//     setIsLoggedIn(true);
//   };
 
//   const logoutHandler = () => {
//     localStorage.setItem('isLoggedIn','0');
//     setIsLoggedIn(false);
//   };

  return (
    <React.Fragment>
      {/* // <AuthContext.Provider value={{isLoggedIn:isLoggedIn,onLogout:logoutHandler}}> */}
      <MainHeader/>
      <main>
        {!ctx.isLoggedIn && <Login/>}
        {ctx.isLoggedIn && <Home/>}
      </main>
      {/* // </AuthContext.Provider> */}
      </React.Fragment>
  );
}

export default App;

index.js
root.render(<AuthContextProvider><App /></AuthContextProvider>);