Showing posts with label GET API. Show all posts
Showing posts with label GET API. 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>
    );
}

Saturday, December 16, 2023

GET API CALL (SIMPLE) in UseEffect HOOK in REACT JS

December 16, 2023 0

 IN REACT JS


import React, { useEffect, useState } from 'react';

export default function App() {
  const txtColor = {
    color: "red",
    fontSize: '20px',
    fontWeight: 'bold',
    paddingTop: '10px',
    textAlign: 'center'
  }

  // Api CAll
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch('https://fakestoreapi.com/products?limit=5')
      .then(res => res.json())
      .then(jsons => {
        console.log(jsons)
        setData(jsons)
      }
      )
   
  }, []);
  console.warn("Data =" + data);
  return (
    <div>
      <h1 style={txtColor} >Hi Avi Singh Calling Api-Application Programming Interface</h1>
      <h1 style={{ ...{ color: 'green' }, ...{ fontWeight: '500' }, ...{ paddingTop: "10px" }, textAlign: 'center' }} > Get Method Call</h1>
      <div style={{width:'500px',alignItems:"center",padding:"50px"}} >
      <table border="1px">
        <tr >
          <td style={{padding:'10px',textAlign:'center'}} >Id</td>
          <td>Title</td>
          <td>Categoryl</td>
          <td>Price</td>
        </tr>
        {
          data.map((item) =>
            <tr>
              <td>{item.id}</td>
              <td>{item.title}</td>
              <td>{item.category}</td>
              <td>{item.price}</td>
            </tr>
          )
        }
      </table>
      </div>
    </div>
  );
}

Thursday, December 14, 2023

Get API CAll (Promise) & Other call (Request) seperate in java script

December 14, 2023 0

 In JAVASCRIPT


async function fetApi(){
      // Get the character ID from the input field
      const characterId = document.getElementById('characterId').value;

      // Construct the SWAPI URL for the specific character
      const swapiUrl = `https://swapi.dev/api/people/${characterId}/`;

      let res=await fetch(swapiUrl);
      let resJson= await res.json();
      return resJson;
    }
    
    // REquest Decode

    async function f1(){
      const jsonData= await fetApi();
      console.log("DATA:-",jsonData);
        // console.log("NAme:-" , jsonData['name']);
    }