-
-
Save navanathjadhav/2e6928a107d7dba53ea6c7925b83cef8 to your computer and use it in GitHub Desktop.
Students table with dynamic data from API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import "./App.scss"; | |
import { Card, Col, Row, Table } from "react-bootstrap"; | |
import axiosInstance from "./http/httpInstance"; | |
function App() { | |
// Hooks | |
const [students, setStudents] = useState([] as any); | |
const [isLoadingStudents, setLoadingStudents] = useState(false); | |
// Fetch students | |
const fetchStudents = () => { | |
setLoadingStudents(true); | |
axiosInstance | |
.get(`/api/students`) | |
.then((response) => { | |
setLoadingStudents(false); | |
setStudents(response.data); | |
}) | |
.catch((error) => { | |
setLoadingStudents(false); | |
console.log(error); | |
}); | |
}; | |
/* | |
* Fetch students when component initiated | |
*/ | |
useEffect(() => { | |
fetchStudents(); | |
}, []); | |
return ( | |
<div className="container-fluid mt-5"> | |
<Row> | |
<Col md={12} lg={12}> | |
<h3>Students</h3> | |
<Card> | |
<Card.Body className="pt-0"> | |
<Table striped hover> | |
<thead> | |
<tr> | |
<th className="bt-none">Name</th> | |
<th className="bt-none">Email</th> | |
<th className="bt-none">Department</th> | |
</tr> | |
</thead> | |
<tbody> | |
{!students.length && !isLoadingStudents && ( | |
<tr className="text-center"> | |
<td colSpan={3}>No students</td> | |
</tr> | |
)} | |
{isLoadingStudents && ( | |
<tr className="text-center"> | |
<td colSpan={3}> | |
<span>Loading...</span> | |
</td> | |
</tr> | |
)} | |
{!isLoadingStudents && | |
students.map((student: any, index: number) => { | |
return ( | |
<tr key={index}> | |
<td>{student.name}</td> | |
<td>{student.email}</td> | |
<td>{student.department}</td> | |
</tr> | |
); | |
})} | |
</tbody> | |
</Table> | |
</Card.Body> | |
</Card> | |
</Col> | |
</Row> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment