Friday, February 2, 2024

POST API (Insert in Site User) with props of Post API Method

February 02, 2024 0

 




import { Box, Button, Divider, InputAdornment, Stack, TextField } from '@mui/material';
import SignPic from '../../asset/images/signin.jpg'
import { Bodytext, Headingtext, SubTitletext, Titletext } from '../../component/utils/Mytext';
import { MYCOLOR } from '../../component/utils/MyColor';

import { getAuth, createUserWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth"
import { app } from "../../firebase"
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import SelectBox from '../../component/Select';
import { useSelector } from 'react-redux';
import { selectUserTypeSlice } from '../../redux toolkit/reducer/UsertypeSlice';

const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
export default function SignUp() {

    const navigate = useNavigate();
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [mobileno, setMobileno] = useState('')
    const [status, setStatus] = useState('')

    const usertype_id = useSelector(selectUserTypeSlice)

    const postApiData = window.postData;


    const signupUser = async () => {
        console.warn("Selected User Type : -", usertype_id)
        console.warn(email, password, mobileno, usertype_id)

        createUserWithEmailAndPassword(
            auth,
            email, //'avisingh@gmail.com',
            password //"Avi123"
        ).then((value) => { console.log(value) });

        let item = { usertype_id, email, password, mobileno, status }
        console.log("Item", item)

        const result = await postApiData(`http://--/api/------`, item);        

        console.log("Post entry Data :", result)

        navigate('/signin');
    }

    // const signupWithGoogle = () => {
    //     signInWithPopup(auth, googleProvider)
    //         .then((user) => console.log("User Created :", user))
    //         .catch((err) => console.error("User Not Created :", err));
    // }

    return (
        <>
            <Box style={{ margin: "10px" }} >
                <img src={SignPic} alt='Sign In Pic' height="350px" width="100%" style={{ borderRadius: '16px', objectFit: 'fill' }} />
            </Box>
            <Stack alignItems="center">
                <Box
                >
                    <Box                       
                    >
                        <Headingtext name={"Join Us Todays"} whiteColor={true} fontFamily='bold' ptop={5} lineHeight={1} />
                        <Titletext name={"Enter your email and password to register "} whiteColor={true} pX={10} lineHeight={1} />
                    </Box>

                    <Box sx={{ marginX: '10px' }}>
                        <Box paddingY={1}>
                            <SelectBox />
                        </Box>
                        <TextField label='Email' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={email} onChange={(e) => setEmail(e.target.value)} />
                        <TextField label='Password' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={password} onChange={(e) => setPassword(e.target.value)} />
                        <TextField label='Mobile No' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={mobileno} onChange={(e) => setMobileno(e.target.value)} />
                        <TextField label='Status' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={status} onChange={(e) => setStatus(e.target.value)} />
                        <Titletext name={"Or "} whiteColor={false} pX={10} lineHeight={1} />

                        <Box>
                            <Button variant='contained' onClick={signupUser} fullWidth sx={{
                                backgroundColor: MYCOLOR.blacktext,
                                '&:hover': {
                                    backgroundColor: MYCOLOR.primary,
                                },
                            }} >Create User</Button>
                        </Box>
                       
                    </Box>

                </Box>

            </Stack>
           
        </>
    );
}

Global Api Call (Create Props Function )

February 02, 2024 0

 Global Api Call

(Create Props Function )


1 // import  public Folder > index.html

   <title>React App</title>

  <script src="%PUBLIC_URL%/apigetdata.js"></script>

2 // in public folder create this file : -     apigetdata.js


//GET Api call Props function

async function apiGetData(url) {
  const swapiUrl = url;
  let res = await fetch(swapiUrl);
  // let resJson = await res.json();
  if (res.ok) {
    let resJson = await res.json();
    return resJson;
  }
  else {
    throw new Error('Network res was not ok.');
  }

  // return resJson;
}


//POST Api call Props function

async function postData(url = "", data = {}) {

  const response = await fetch(url, {

    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin

    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

// postData("http://surevih.in/api/posthello", { answer: 42 }).then((data) => {
//   console.log(data); // JSON data parsed by `data.json()` call
// });

POST API (Insert in Site User) Simple Way

February 02, 2024 0

 POST API (Insert in Site User)

 Simple Way


import { Box, Button, Divider, InputAdornment, Stack, TextField } from '@mui/material';
import SignPic from '../../asset/images/signin.jpg'
import { Bodytext, Headingtext, SubTitletext, Titletext } from '../../component/utils/Mytext';
import { MYCOLOR } from '../../component/utils/MyColor';

import { getAuth, createUserWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth"
import { app } from "../../firebase"
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import SelectBox from '../../component/Select';
import { useSelector } from 'react-redux';
import { selectUserTypeSlice } from '../../redux toolkit/reducer/UsertypeSlice';

const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();

export default function SignUp() {

    const navigate = useNavigate();
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [mobileno, setMobileno] = useState('')
    const [status, setStatus] = useState('')

    const usertype_id = useSelector(selectUserTypeSlice)


    const signupUser = async () => {
        console.warn("Selected User Type : -", usertype_id)
        console.warn(email, password, mobileno, usertype_id)
        createUserWithEmailAndPassword(
            auth,
            email, //'avisingh@gmail.com',
            password //"Avi123"
        ).then((value) => { console.log(value) });

        // Simple Way
        let item = { usertype_id, email, password, mobileno, status }
        console.log("Item", item)
        let result = await fetch(`http://------/api/-----`, {
            method: 'POST',
            mode: "cors",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            },
            body: JSON.stringify(item)
        })
        result = await result.json()
       
        console.log("Post entry Data :", result)

        navigate('/signin');
    }

    return (
        <>
            <Box style={{ margin: "10px" }} >
                <img src={SignPic} alt='Sign In Pic' height="350px" width="100%" style={{ borderRadius: '16px', objectFit: 'fill' }} />
            </Box>
            <Stack alignItems="center">
                <Box                   
                >
                    <Box                       
                    >
                        <Headingtext name={"Join Us Todays"} whiteColor={true} fontFamily='bold' ptop={5} lineHeight={1} />
                        <Titletext name={"Enter your email and password to register "} whiteColor={true} pX={10} lineHeight={1} />
                    </Box>

                    <Box sx={{ marginX: '10px' }}>

                        <Box paddingY={1}>
                            <SelectBox />
                        </Box>
                     

                        <TextField label='Email' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={email} onChange={(e) => setEmail(e.target.value)} />
                        <TextField label='Password' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={password} onChange={(e) => setPassword(e.target.value)} />
                        <TextField label='Mobile No' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={mobileno} onChange={(e) => setMobileno(e.target.value)} />
                        <TextField label='Status' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={status} onChange={(e) => setStatus(e.target.value)} />
                        <Titletext name={"Or "} whiteColor={false} pX={10} lineHeight={1} />

                        <Box>
                            <Button variant='contained' onClick={signupUser} fullWidth sx={{
                                backgroundColor: MYCOLOR.blacktext,
                                '&:hover': {
                                    backgroundColor: MYCOLOR.primary,
                                },
                            }} >Create User</Button>
                        </Box>
                       

                    </Box>

                </Box>

            </Stack>
           

        </>
    );
}

Lift Shift Up (Child to parent data transfer)

February 02, 2024 0

 Lift Shift Up 

(Child to parent data transfer)


// Child Component



import { FormControl, InputLabel, MenuItem, Select } from "@mui/material";
import { useEffect, useState } from "react";

export default function Selectbox({ sendDataToParent }) {

    const [data, setData] = useState(['']);
    const [showuser, setShowUser] = useState('');
    const GetApiData = window.apiGetData;

    useEffect(() => {

        const handleFetchCharacter = async () => {
            try {
                // const jsonData = await fetApi();
                const jsonData = await GetApiData(`http://-----/api/-------`);
                const result = jsonData['result'];
                console.log("Result :-", result);
                setData(result);
            } catch (error) {
                // Handle error, e.g., show an error message
                console.error('Error fetching character:', error);
            }
        };

        handleFetchCharacter();
    }, [GetApiData]);

    const handleChange = (event) => {
        // console.log("data  :" , jsonvalue);
        const selectedValue = event.target.value;
        console.log("Target Value :- ", event.target.value);

        setShowUser(event.target.value);
        sendDataToParent(selectedValue);
    };



    // console.log("All types data", data)

    return (
        <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">User Type</InputLabel>
            <Select
                labelId="demo-simple-select-label"
                id="demo-simple-select"
                value={showuser}
                label="Show User Type"
                onChange={handleChange}
            >
                {
                    data.map((item, index) =>
                        index !== 0 && (
                            <MenuItem key={item.id} value={item.id}>{item.usertype}</MenuItem>
                        )
                    )
                }
            </Select>

        </FormControl>
    );
}


// Parent Component



import { Box, Button, Divider, InputAdornment, Stack, TextField } from '@mui/material';
import SignPic from '../../asset/images/signin.jpg'
import { Bodytext, Headingtext, SubTitletext, Titletext } from '../../component/utils/Mytext';
import { MYCOLOR } from '../../component/utils/MyColor';

import { getAuth, createUserWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth"
import { app } from "../../firebase"
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import SelectBox from '../../component/Select';


const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();


export default function SignUp() {
    const navigate = useNavigate();
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [mobileno, setMobileno] = useState('')

    const [usertype, setUsertype] = useState('')

    const handleSelectData = (dataFromChild) => {
        setUsertype(dataFromChild);
    }


    const signupUser = () => {
        console.warn(email, password, mobileno, usertype)
        createUserWithEmailAndPassword(
            auth,
            email, //'avisingh@gmail.com',
            password //"Avi123"
        ).then((value) => { console.log(value) });

        // navigate('/signin');
    }

    const signupWithGoogle = () => {
        signInWithPopup(auth, googleProvider)
            .then((user) => console.log("User Created :", user))
            .catch((err) => console.error("User Not Created :", err));

    }

    return (
        <>
            <Box style={{ margin: "10px" }} >
                <img src={SignPic} alt='Sign In Pic' height="350px" width="100%" style={{ borderRadius: '16px', objectFit: 'fill' }} />
            </Box>
            <Stack alignItems="center">
                <Box
                    sx={{
                        position: 'absolute',
                        zIndex: 0,
                        top: "220px",
                        backgroundColor: MYCOLOR.whitetext,
                        width: '500px',
                       
                    }}
                >

                    <Box sx={{ marginX: '10px' }}>
                        <Box paddingY={1}>
                            <SelectBox sendDataToParent={handleSelectData} />
                        </Box>
                        <h6>Data from Child: {usertype}</h6>
                       

                        <TextField label='Email' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={email} onChange={(e) => setEmail(e.target.value)} />
                        <TextField label='Password' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={password} onChange={(e) => setPassword(e.target.value)} />
                        <TextField label='Mobile No' variant='standard' fullWidth sx={{ marginBottom: '10px' }} value={mobileno} onChange={(e) => setMobileno(e.target.value)} />


                        <Titletext name={"Or "} whiteColor={false} pX={10} lineHeight={1} />

                        <Box sx={{ marginBottom: '10px' }} >
                            <Button variant='contained' onClick={signupWithGoogle} sx={{
                                backgroundColor: MYCOLOR.blacktext,
                                '&:hover': {
                                    backgroundColor: MYCOLOR.primary,
                                },
                            }}>Sign Up Google</Button>
                        </Box>

                        <Box>
                            <Button variant='contained' onClick={signupUser} fullWidth sx={{
                                backgroundColor: MYCOLOR.blacktext,
                                '&:hover': {
                                    backgroundColor: MYCOLOR.primary,
                                },
                            }} >Create User</Button>
                        </Box>
                        <Box sx={{ marginY: '10px', display: 'flex', alignItems: 'baseline' }}>
                            <Titletext name={"Already have a member? "} whiteColor={false} lineHeight={1} />
                            <Button onClick={() => navigate('/signin')} sx={{
                                color: 'blue',
                                fontWeight: 'bold'
                            }} >LogIn</Button>
                        </Box>

                    </Box>

                </Box>

            </Stack>
           
        </>
    );
}