0% found this document useful (0 votes)
26 views

WT Unit-5 API With React Js

Uploaded by

KAVAL VYAS
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

WT Unit-5 API With React Js

Uploaded by

KAVAL VYAS
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Web Technology (WT)

(2101CS304)

Unit-05
Consuming API in
ReactJS

Prof. Arjun V. Bala


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9624822202
 Outline
Looping

Hooks
Forms
Consuming API
Hooks
 Hooks are a new addition in React 16.8.
 Using Hooks you can use state and other React features without writing a class, because of
hooks class components are no longer needed.
 Hooks allow us to "hook" into React features such as state and lifecycle methods.
 We can use built-in hooks or create our custom hook if we want.
 If we want to use any of the built-in hooks we need to import them from the react.
 There are 3 rules to use hooks
 Hooks can only be called inside React function components.
 Hooks can only be called at the top level of a component.
 Hooks cannot be conditional
 Some important built-in hooks are
 useState  useReducer
 useEffect  useCallback
 useContext  useMemo
 useRef
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 3
“useState” Hook
 The React useState Hook allows us to track state in a function component.
 State generally refers to data or properties that need to be tracking in an application.
 In order to use useState hook we first need to import it from the react.
1 import { useState } from 'react';

 In order to initialize the state we can call useState in our function.


1 const [ count , setCount ] = useState(0);

 Note: here we are destructuring the returned values from useState.


 useState accepts an initial state and returns two values:
 The current state.
 A function that updates the state.
 To read the state we can simply use count variable in our function.
 To update the state we must use the function returned from the useState call
1 setCount(20); // this is valid
2 count = 20; // this is not valid
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 4
“useEffect” Hook
 The useEffect Hook allows you to perform side effects in your components.
 Some examples of side effects are:
 fetching data
 directly updating the DOM
 Timers
 Etc…
 useEffect accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)

 We can perform side effects in our component specified at the function argument.
 Here notice that this function will be executed each time we render the component.
 There are several ways to control when side effects run using the second argument.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 5


“useEffect” Hook (Cont.)
 No dependency passed
1 useEffect(() => {
2 //Runs on every render
3 });

 An empty array:
1 useEffect(() => {
2 //Runs only on the first render
3 }, []);

 Dependency passed (dependency can be props, state etc…)


1 useEffect(() => {
2 //Runs when there is a change in a or b
3 }, [a,b]);

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 6


Forms
 HTML form elements work a bit differently from other DOM elements in React, because
form elements naturally keep some internal state.
 For example, this form in plain HTML accepts a single name:
1 <form>
2 <label>
3 Name:
4 <input type="text" name="name" />
5 </label>
6 <input type="submit" value="Submit" />
7 </form>
 This form has the default HTML form behavior of browsing to a new page when the user
submits the form.
 If you want this behavior in React, it just works. But in most cases, it’s convenient to have a
JavaScript function that handles the submission of the form and has access to the data that the
user entered into the form.
 The standard way to achieve this is with a technique called “controlled components”.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 7


Controlled Components
 In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their
own state and update it based on user input.
 In React, mutable state is typically kept in the state property of components, and only updated
with setState().
 We can combine the two by making the React state be the “single source of truth”. Then the
React component that renders a form also controls what happens in that form on subsequent
user input.
 An input form element whose value is controlled by React in this way is called a “controlled
component”.
 For example, if we want to make the previous example log the name when it is submitted, we
can write the form as a controlled component as shown in next slide.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 8


Controlled Components (Example)
1 function MyForm() {
2 const [name, setName] = useState("");
3
4 function handleSubmit(e){
5 console.log(name);
6 e.preventDefault(); // this method will stop form to submit and JS will have control
7 }
8
9 return (
10 <form onSubmit={handleSubmit}>
11 <input
12 type="text"
13 value={name}
14 onChange={(e) => setName(e.target.value)}
15 />
16 <input type="submit" />
17 </form>
18 )
19 }

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 9


Handling multiple inputs using useState Hook
1 function MyForm() {
2 const [data, setData] = useState({UserName:"",Password:""});
3
4 function handleSubmit(e){
5 console.log(data.UserName + " & " + data.Password);
6 e.preventDefault();
7 }
8
9 return (
10 <form onSubmit={handleSubmit}>
11 <input type="text" name="UserName" value={data.UserName}
12 onChange={(e) => setData({...data, UserName:e.target.value})} />
13 <input type="text" name="Password" value={data.Password}
14 onChange={(e) => setData({...data, Password:e.target.value})} />
15 <input type="submit" />
16 </form>
17 )
18 }

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 10


CRUD API Operation using React
 We are going to perform 5 operations, we will name it getAll, getByID, insert, update and
delete.
 In our API we have following fields,
 FacultyID
 FacultyName
 FacultyImage
 FacultyDepartment
 FacultySalary

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 11


getAll, getByID Operation using API
1 function Faculties(){ 1 function FacultyDetail(){
Faculties.js (getAll)

2 const [faculties,setFaculties] = useState([]); 2 const [faculty,setFaculty] = useState({});


3 3 const { id } = useParams();

FacultyDetail.js
(getByID)
4 useEffect(()=>{ 4 useEffect(()=>{
5 let apiUrl = "API URL HERE"; 5 let apiUrl = "API URL HERE/"+id;
6 fetch(apiUrl) 6 fetch(apiUrl)
7 .then((res)=>res.json()) 7 .then((res)=>res.json())
8 .then((res)=>setFaculties(res.records)); 8 .then((res)=>setFaculty(res));
9 },[]) 9 },[]);
10 10
11 var result = faculties.map((f)=>{ 11 return(
12 return( 12 <>
13 <> 13 <h1>{faculty.FacultyName}</h1>
14 <Link to={"/faculties/"+f.FacultyID}> 14 <p>{ faculty.FacultyDetail }</p>
15 <div class="col-3"> 15 <img src={faculty.FacultyImage} />
16 <img class="img-fluid" src={f.FacultyImage} /> 16 // etc.....
17 <h3>{f.FacultyName}</h3> 17 </>
18 </div> 18 );
19 </Link> 19
20 </>); 20 }
21 })
22
23 return( 1 root.render(

Index.js (only render


24 <> 2 <BrowserRouter>
25 <div class="container"> 3 <Routes>

method)
26 <div class="row"> 4 <Route path='/faculties' element={<Faculties/>} />
27 {result} 5 <Route path='/faculties/:id' element={<FacultyDetail/>} />
28 </div> 6 </Routes>
29 </div> 7 </BrowserRouter>
30 </> 8 );
31 );
32 } Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 12
Index.js
1 import {React, useEffect, useState} from "react";
2 import { Component } from "react";
3 import { createRoot } from "react-dom/client";
Index.js

4 import { BrowserRouter, Link, Outlet, Route, Routes, useNavigate, useParams } from "react-router-dom";
5
6 const root = createRoot(document.getElementById('root'));
7
8 // All the components will be placed here
9
10 function Layout(){
11 return(<>
12 <Link to="/"> Home </Link> {" "}
13 <Link to="/faculties"> Display All Faculty </Link> {" "}
14 <Link to="/faculties/add"> Add Faculty </Link> {" "}
15 <br/>
16 <Outlet />
17 <h1>Footer</h1>
18 </>);
19 }
20
21 root.render(<BrowserRouter>
22 <Routes>
23 <Route path="/" element={<Layout />}>
24 <Route path="/faculties" element={<GetAllFaculty />} />
25 <Route path="/faculties/:id" element={<DetailFaculty />} />
26 <Route path="/faculties/add" element={<AddFaculty />} />
27 <Route path="/faculties/edit/:id" element={<EditFaculty />} />
28 </Route>
29 </Routes>
30 </BrowserRouter>);

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 13


getAll, getByID & delete
1 function GetAllFaculty(){ 1 function DetailFaculty(){
2 const navigate = useNavigate(); 2 const navigate = useNavigate();
3 const apiUrl = "apiURLHere"; 3 const param = useParams();

getByID
4 4
getAll

5 const [data,setData] = useState([]); 5 const apiUrl = "apiUrlHere";


6 6
7 useEffect(()=>{ 7 const [data,setData] = useState({});
8 fetch(apiUrl) 8
9 .then(res=>res.json()) 9 useEffect(()=>{
10 .then(res=>setData(res)); 10 fetch(apiUrl+"/"+param.id,{method:"GET"})
11 },[]); 11 .then(res=>res.json())
12 12 .then(res=>setData(res));
13 const formatedData = data.map((fac)=>{ 13 },[]);
14 return <h1 onClick={()=>{ 14
15 navigate('/faculties/'+fac.id); 15 return <>
16 }}>{ fac.FacultyName }</h1> 16 <h1>FacultyName : {data.FacultyName} </h1>
17 }); 17 <h1>FacultySalary : {data.FacultySalary} </h1>
18 18 <img src={data.FacultyImage} />
19 19 <button onClick={()=>{
20 return(<> 20 fetch(apiUrl+"/"+param.id,{method:"DELETE"})
21 {formatedData} 21 .then(res=>{
22 </>); 22 navigate('/faculties');
23 23 });
24 } 24 }}>Delete</button>
25 <button onClick={()=>{
26 navigate('../faculties/edit/'+param.id);
27 }}>Edit</button>
28 </>;
29 }

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 14


Insert & update
1 function AddFaculty(){ 1 function EditFaculty(){
2 const navigate = useNavigate(); 2 const param = useParams();
3 const apiUrl = "apiUrlHere"; 3 const navigate = useNavigate();
4 4 const apiUrl = "apiUrlHere";

update
insert

5 const [data, setData] = useState({FacultyName:""}); 5


6 return(<> 6 useEffect(()=>{
7 <input type="text" onChange={(e)=>{ 7 fetch(apiUrl+"/"+param.id,{method:"GET"})
8 setData({...data,FacultyName:e.target.value}); 8 .then(res=>res.json()).then(res=>setData(res));
9 }} /> 9 },[]);
10 <input type="text" onChange={(e)=>{ 10
11 setData({...data,FacultyImage:e.target.value}); 11 const [data, setData] = useState({});
12 }} /> 12 return(<>
13 13 <input type="text" value={data.FacultyName} onChange={(e)=>{
14 // all input fields here 14 setData({...data,FacultyName:e.target.value});
15 15 }} />
16 <input type="button" value="Add Faculty" 16 // all input fields here
17 onClick={()=>{ 17 <input type="button" value="Edit Faculty" onClick={()=>{
18 fetch(apiUrl,{ 18 fetch(apiUrl+"/"+param.id,{
19 method:"POST", 19 method:"PUT",
20 body:JSON.stringify(data), 20 body:JSON.stringify(data),
21 headers:{ 21 headers:{
22 "Content-Type":"application/json" 22 "Content-Type":"application/json"
23 } 23 }
24 }) 24 }).then((res)=>{
25 .then((res)=>{ 25 navigate('/faculties');
26 navigate('/faculties'); 26 })
27 }) 27 }} />
28 }} /> 28 </>);
29 </>); 29 }
30 }

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 05 – Consuming API in React 15

You might also like