Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Front-end insem-lab exam

2100031755
M.Srinivasa Reddy

App.js

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


import './App.css';
import axios from 'axios';

// Enhanced user interface component with improved usability:


function App() {
const [users, setUsers] = useState([]);
const [filterUserId, setFilterUserId] = useState(null);
const [userRoles, setUserRoles] = useState([]); // Array to store fetched roles

// Fetch user information and roles (assuming 'role' exists in user data):
useEffect(() => {
fetchUserInformation();
fetchUserRoles(); // Added separate role fetching
}, []);

const fetchUserInformation = async () => {


try {
const response = await
axios.get('https://jsonplaceholder.typicode.com/users');
setUsers(response.data);
} catch (error) {
console.error('Failed to fetch user information:', error);
}
};

// Optimized role fetching with potential performance improvement:


const fetchUserRoles = async () => {
try {
const response = await
axios.get('https://jsonplaceholder.typicode.com/users'); // Assuming roles are
available in the same API endpoint
const uniqueRoles = [...new Set(response.data.map((user) => user.role))]; //
Extract unique roles using Set for potential performance improvement
setUserRoles(uniqueRoles);
} catch (error) {
console.error('Failed to fetch user roles:', error);
}
};

const displayUserInformation = () => {


if (!users.length) {
return <div>No user information available.</div>;
}

// Efficient sorting for large datasets using built-in sort method:


const sortedUsers = users.slice().sort((a, b) => a.id - b.id);

// Handle missing 'role' property gracefully:


const userRolesDisplay = userRoles.length
? userRoles.map((role) => <option key={role}>{role}</option>) // Option
elements
: <option key="no-roles">No roles available</option>; // Fallback option

return (
<div className="App">
<h1>User Information</h1>
<select
value={filterUserId}
onChange={(event) => setFilterUserId(event.target.value)}
>
<option value={null}>All Users</option>
{userRolesDisplay}
</select>
{displayFilteredUsers(sortedUsers)}
</div>
);
};

const displayFilteredUsers = (users) => {


return (
<table>
<thead>
<tr>
<th>User ID</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.role}</td>
</tr>
))}
</tbody>
</table>
);
};

return (
<div className="App">
{displayUserInformation()}
</div>
);
}

export default App;

output:-

You might also like