0% found this document useful (0 votes)
5 views4 pages

Rest API Example With Code

This document describes a React component called EmployeeForm that collects employee information through prompt dialogs and submits it to a REST API. It includes detailed explanations of the code structure, input validation, and error handling. The component utilizes the fetch() method to send a POST request to a dummy API and handles the API response accordingly.

Uploaded by

Saad Ilyas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Rest API Example With Code

This document describes a React component called EmployeeForm that collects employee information through prompt dialogs and submits it to a REST API. It includes detailed explanations of the code structure, input validation, and error handling. The component utilizes the fetch() method to send a POST request to a dummy API and handles the API response accordingly.

Uploaded by

Saad Ilyas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

React REST API Example – Employee Information Form

This document explains a React component that collects Employee information via user
input (using prompt dialogs) and sends it to a REST API. It also contains detailed
explanations of each part of the code.

Code

import React from "react";

function EmployeeForm() {
const handleSubmit = () => {
// Prompt user for inputs
const name = prompt("Enter Employee Name:");
const bloodGroup = prompt("Enter Blood Group:");
const email = prompt("Enter Email:");

// Check if any field is empty


if (!name || !bloodGroup || !email) {
alert("All fields are required!");
return;
}

// Create object with collected info


const EmployeeInfo = {
name,
bloodGroup,
email
};

[Link]("Collected Employee Info:", EmployeeInfo);

// Send data to REST API using fetch


fetch("[Link] {
method: "POST",
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: [Link](EmployeeInfo)
})
.then((response) => {
if (![Link]) {
throw new Error("Failed to submit");
}
return [Link]();
})
.then((data) => {
[Link]("Response from API:", data);
alert("Employee Information submitted successfully!");
})
.catch((error) => {
[Link]("Error:", error);
alert("Error submitting Employee Information.");
});
};

return (
<div style={{ padding: "20px" }}>
<h2>Employee Information Form</h2>
<button onClick={handleSubmit}>Enter Employee Information</button>
</div>
);
}

export default EmployeeForm;

Button Click → triggers handleSubmit().

prompt() asks for:

 Employee Name
 Blood Group
 Email

Creates a JavaScript object with collected data.

Sends a POST request using fetch()


to:[Link]

Detailed Explanation

Component Definition
Defines a functional React component named EmployeeForm.
Button Click Event
The button triggers handleSubmit() when clicked.

handleSubmit Function
Handles collecting input, validating, sending to API, and showing alerts.

Collecting Input with prompt()


Uses browser prompts to get Employee Name, Blood Group, and Email.

Input Validation
Checks if any field is empty; stops execution if so.

Creating the Data Object


Stores collected values in a JavaScript object for sending.

Sending Data to REST API


Uses fetch() to send a POST request with JSON data to the API.

Handling API Response


Processes the API's response and checks for errors.

Showing Success Message


Displays a success alert when submission is successful.

Handling Errors
Catches and displays any errors that occur during the request.

fetch("[Link] {
method: "POST",
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: [Link](studentInfo)
})

fetch() is a built-in JavaScript function for making HTTP requests.

URL: [Link] is a dummy API for testing.

Method: "POST" means we are sending new data.

Headers: Tell the API we are sending JSON.

body: We convert studentInfo to JSON string using [Link]()


.then((response) => {
if (![Link]) {
throw new Error("Failed to submit");
}
return [Link]();
})
.then() runs after the request is complete.

If the API doesn’t return a success code (200–299), we throw an error.

Otherwise, we convert the API response to JSON.

.then((data) => {
[Link]("Response from API:", data);
alert("Student Information submitted successfully!");
})
This runs if the request is successful.

We log the API’s response and show an alert confirming success.

You might also like