Showing posts with label API CALL. Show all posts
Showing posts with label API CALL. Show all posts

Friday, February 2, 2024

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
// });

Thursday, February 1, 2024

UserType Get Data

February 01, 2024 0

 UserType Get Data 

with Get Api


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

export default function Selectbox(props) {

    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://surevih.in/api/allusertype`);
                const result = jsonData['usertypes'];
                console.log("Re;-", 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);
        console.log("Target Value :- ", event.target.value);
        setShowUser(event.target.value);
    };

    // 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}
            >
                // all list show
                {
                    data.map((item) =>
                        <MenuItem key={item.id} value={item.id}>{item.usertype}</MenuItem>
                    )
                }

                // Admin element not show in List
                
                   {
                    data.map((item, index) =>
                        index !== 0 && (
                            <MenuItem key={item.id} value={item.id}>{item.usertype}</MenuItem>
                        )
                    )
                }
            </Select>

        </FormControl>
    );
}

Friday, January 12, 2024

Json Data Sender in body : JSON.stringify(data)

January 12, 2024 0

 Json Data Sender in body : JSON.stringify(data)


// in Form

const [formData, setFormData] = useState({
        workername: "",
        workertype: "",
    });

calling : -
        body: JSON.stringify(formData),


// Without Form : - input field Direct

Type 1

const [workername, setWorkername] = useState();
const [workertype, setWorkertype] = useState();

console.log(workername, workertype);

calling : -

body: JSON.stringify({ "workername": workername, "workertype": workertype }),

<TextField
                required
                label="Worker Name"
                id='workername'
                type='text'
                value={workername}
                onChange={(e) => setWorkername(e.target.value)}
            />

Type 2

const [workername, setWorkername] = useState();
const [workertype, setWorkertype] = useState();

const data = {
            workername,
            workertype
            // Add more properties as needed
        };

calling : -

body: JSON.stringify(data),

<TextField
                required
                label="Worker Name"
                id='workername'
                type='text'
                value={workername}
                onChange={(e) => setWorkername(e.target.value)}
            />


Create a new data in database without form (POST API)

January 12, 2024 0

 Create a new data in database without form (POST API)


export default function ButtonText() {

    const [workername, setWorkername] = useState();
    const [workertype, setWorkertype] = useState();

    const [open, setOpen] = useState(false);

    const handleButtonClick = async () => {
        console.log(workername, workertype);

        // or
        
        const data = {
            workername,
            workertype
        };
        try {
            const response = await fetch("http://surevih.in/api/workerprofile", {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ "workername": workername, "workertype": workertype }),
                  
        // or

                body: JSON.stringify(data),
            });
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const result = await response.json();
            console.log('Product created successfully:', result);
        } catch (error) {
            console.error('Error creating product:', error.message);
        }
    };

    const handleClose = () => {
        setOpen(false);
    };
    return (
        <>
            <Box display='flex' xs={12} paddingBottom={2}  >
                <Typography paddingLeft={3} variant='h4' >Create Account without Form</Typography>
            </Box>
            <TextField
                required
                label="Worker Name"
                id='workername'
                defaultValue=''
                variant="outlined"
                margin="normal"
                fullWidth
                type='text'
                value={workername}
                onChange={(e) => setWorkername(e.target.value)}
            />

            <TextField
                required
                label="Worker type"
                id='workertype'
                defaultValue=''
                variant="outlined"
                margin="normal"
                fullWidth
                // type='number'
                value={workertype}
                onChange={(e) => setWorkertype(e.target.value)}
            />

            {/* <Subtitletext name={'User Type'} color="true" /> */}

            <Button fullWidth={true} style={{ color: "black", backgroundColor: 'pink' }}
                type="submit"
                variant="contained"
                margin="normal"
                onClick={handleButtonClick}
            >
                Create Account
            </Button>

            </>
    );
}

Show Data single Profile from Database with Form (GET API With ID)

January 12, 2024 0

 Show Dat single Profile from Database  with Form


export default function Text() {

    const [formData, setFormData] = useState({
        workername: "",
        workertype: "",
    });
    useEffect(() => {
        // Fetch user profile data from the API and populate the form
        const fetchUserProfile = async () => {
            try {
                const response = await fetch('http://------/---/--/worker/2', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        // Add any authorization headers if required
                    },
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                const userData = await response.json();
                // console.log(userData['worker']);
                setFormData(userData['worker']);
            } catch (error) {
                console.error('Error fetching user profile:', error.message);
            }
        };

        fetchUserProfile();
    }, []);
    console.log("Data: ", formData);

    const handleInputChange = (e) => {
        setFormData({ ...formData, [e.target.id]: e.target.value, });
    };

    const handleFormSubmit = async (e) => {
        e.preventDefault();
    }

    const [open, setOpen] = useState(false);
    const handleButtonClick = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };
    return (
        <>
            <form onSubmit={handleFormSubmit} >
                <Box display='flex' xs={12} paddingBottom={2}  >
                    <Typography paddingLeft={3} variant='h4' >Create Account</Typography>
                </Box>

                <TextField
                    required
                    label="Worker Name"
                    id='workername'
                    defaultValue=''
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    type='text'
                    value={formData.workername}
                    onChange={handleInputChange}
                />

                <TextField
                    required
                    label="Worker type"
                    id='workertype'
                    defaultValue=''
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    // type='number'
                    value={formData.workertype}
                    onChange={handleInputChange}
                />

                {/* <Subtitletext name={'User Type'} color="true" /> */}

                <Button fullWidth={true} style={{ color: "black", backgroundColor: 'pink' }}
                    type="submit"
                    variant="contained"
                    margin="normal"
                    onClick={handleButtonClick}
                >
                    Create Account
                </Button>

                <Dialog open={open} onClose={handleClose}>
                    <DialogTitle>Alert</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            User Logined Successful.
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose}>OK</Button>
                        <Button onClick={handleClose}>Closed</Button>
                    </DialogActions>
                </Dialog>
            </form>

        </>
    );
}

Create a new Data in Database with Form (POST API)

January 12, 2024 0

Create a new Data in Database with Form  


export default function Text() {

    const [formData, setFormData] = useState({
        workername: "",
        workertype: "",
    });

    const handleInputChange = (e) => {
        setFormData({ ...formData, [e.target.id]: e.target.value, });
    };

    const handleFormSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await fetch("http://--------/api/workerprofile", {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const result = await response.json();
            console.log('Product created successfully:', result);
        } catch (error) {
            console.error('Error creating product:', error.message);
        }
    }
   
    const [open, setOpen] = useState(false);
    const handleButtonClick = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };
    return (
        <>
            <form onSubmit={handleFormSubmit} >
                <Box display='flex' xs={12} paddingBottom={2}  >
                    <Typography paddingLeft={3} variant='h4' >Create Account</Typography>
                </Box>

                <TextField
                    required
                    label="Worker Name"
                    id='workername'
                    defaultValue=''
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    type='text'
                    value={formData.workername}
                    onChange={handleInputChange}
                />

                <TextField
                    required
                    label="Worker type"
                    id='workertype'
                    defaultValue=''
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    // type='number'
                    value={formData.workertype}
                    onChange={handleInputChange}
                />

                {/* <Subtitletext name={'User Type'} color="true" /> */}

                <Button fullWidth={true} style={{ color: "black", backgroundColor: 'pink' }}
                    type="submit"
                    variant="contained"
                    margin="normal"
                    onClick={handleButtonClick}
                >
                    Create Account
                </Button>

                <Dialog open={open} onClose={handleClose}>
                    <DialogTitle>Alert</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            User Logined Successful.
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose}>OK</Button>
                        <Button onClick={handleClose}>Closed</Button>
                    </DialogActions>
                </Dialog>
            </form>

        </>
    );
}