Terminal Exam - Web Engg - SP23 - Solution (1) (1)
Terminal Exam - Web Engg - SP23 - Solution (1) (1)
Instructions:
1. Attempt on question paper. Attempt all of them. Read the question carefully, understand the
question, and then attempt it.
2. Use Rough Work space to finalize the answer and then write in the given space. Cutting
and overwriting will not be evaluated, so carefully plan the answers.
3. Write optimized and minimal code to achieve the desired functionality. Writing poor code
will not get full marks. It is not all about ‘it works’, it should work in the best optimal way.
4. After asked to commence the exam, please verify that you have Eighteen (18) different
printed pages including this title page. There are a total of 3 questions.
5. Use permanent ink pens only. Any part done using soft pencil will not be marked and
cannot be claimed for rechecking.
Marks Obtained
Fill the table for the correct option in uppercase letters ONLY. Overwriting and cutting will not give
you any score.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
B
or D C D A D A A A D C B B C B A B A B C
C
1. In React, which of the following is the correct way to update the state based on the previous state?
a) this.state = state + 1;
b) this.setState({ count: this.state.count + 1 });
c) this.setState(prevState => ({ count: prevState.count + 1 }));
d) this.setState({ count: this.state.count++ });
3. Which block of code or a hook is used to fetch data from an API in a React functional component?
a) Using the "fetch" method inside the component's render function.
b) Using the "componentDidMount" lifecycle method.
c) Using the "useEffect" hook.
d) Using the "fetch" method at the root of a component.
4. How can you pass data from a child component to its parent component in React?
a) By using the "this.props" object.
b) By using the "setState" method.
c) By using the "useContext" hook.
d) By passing a callback function as a prop.
7. When should you use the useReducer hook instead of the useState hook in React?
a) When managing complex state logic or multiple related values.
b) When working with form inputs.
c) When handling asynchronous operations.
d) When using context in functional components
Page 2 of 27
8. How can you trigger a re-render of a React component?
a) By changing the state of a component.
b) By modifying the component's props.
c) By using the render method.
d) React components automatically re-render when their state or props change
10. Which React hook is commonly used to handle complex state logic in functional components?
a) useState
b) useEffect
c) useContext
d) useReducer
13. How is data provided to components using the React Context API?
a) By passing data as props from parent to child components
b) By defining a context object and using a Provider component to wrap the desired components
c) By using Redux for state management
d) By using the useState hook to create a global state object
16. What is the primary routing component used in React Routing v6?
a) BrowserRouter
b) Switch
c) Router
d) Route
Page 3 of 27
17. Which hook is used to navigate programmatically in React Routing v6?
a) useHistory
b) useNavigate
c) useLocation
d) useParams
18. How do you define a route with parameters in React Routing v6?
a) <Route path="/users/:id" element={<UserDetail />} />
b) <Route path="/users/{id}" element={<UserDetail />} />
c) <Route path="/users/:id" component={UserDetail} />
d) <Route path="/users/{id}" component={UserDetail} />
20. It is a recommended approach to store JWT Secrets an env file. _______ package is used to read env file?
a) jsontoken
b) jwt
c) dotenv
d) none of the above
Page 4 of 27
Question 2 [5 x 4 = 20 Marks]
Consider a Clinic System application that manages the data of doctors using ExpressJS and APIs. The
doctor entity has the following attributes: Name, Designation, and Specialization. You are tasked with
implementing the API routes for performing CRUD operations on the doctors' data.
While writing code, any data source can be selected but specify which data source is used in the
implementation.
Please provide the sample API calls for the routes that need to be implemented in ExpressJS to achieve
the following functionalities:
Page 5 of 27
{
id: 2,
name: "Dr. Sarah Johnson",
designation: "Pediatrician",
specialization: "Pediatrics"
}
];
Page 6 of 27
2) Retrieve a specific doctor's information:
Endpoint: GET /api/doctors/:id
Sample Request: GET /api/doctors/123
Sample Response:
{
"name": "Dr. John Smith",
"designation": "Senior Consultant",
"specialization": "Cardiology"
}
if (doctor) {
res.json(doctor);
} else {
res.status(404).json({ error: 'Doctor not found' });
}
});
Page 7 of 27
const newDoctor = {
id: doctors.length + 1,
name,
designation,
specialization
};
doctors.push(newDoctor);
res.status(201).json(newDoctor);
});
Page 8 of 27
4) Update an existing doctor's information:
Endpoint: PUT /api/doctors/:id
Sample Request: Sample Response:
PUT /api/doctors/123 {
Content-Type: application/json "id": "123",
"name": "Dr. John Smith",
{ "designation": "Consultant",
"name": "Dr. John Smith", "specialization": "Cardiology"
"designation": "Consultant", }
"specialization": "Cardiology"
}
if (doctor) {
doctor.name = name;
doctor.designation = designation;
doctor.specialization = specialization;
res.json(doctor);
} else {
res.status(404).json({ error: 'Doctor not found' });
}
});
5) Delete a doctor:
Endpoint: DELETE /api/doctors/:id
Sample Request: DELETE /api/doctors/123
Sample Response:
{
"id": "123",
"message": "Doctor deleted successfully."
}
Page 9 of 27
Note: Please provide the sample API calls for the routes mentioned above, considering the appropriate
HTTP methods and endpoints.
app.delete('/api/doctors/:id', (req, res) => {
const doctorId = parseInt(req.params.id);
Page 10 of 27
Question 3 [60 Marks]
console.log('State is Ready!')
useEffect(() => {
}, [ready]);
console.log("Returning JSX")
return (
<div>
</div>
);
a) What will be the output on console when component is rendered first time? (2 Marks)
State is Ready!
Returning JSX
b) What will be the output on console when button is clicked for the first time? (2 Marks)
State is Ready!
Returning JSX
Page 11 of 27
c) What will be printed on the web page when the button is clicked for the first time? (2 Mark)
Ready!
Page 12 of 27
2) What will be printed on the screen? If there is any error, specify that. (2 Marks)
Output:
Item 1
Item 2
function PostList({__posts_}) {
return (
<div>
<h2>Posts</h2>
{ posts.length === 0 ? (
<p>No posts available.</p>
):(
<ul>
{ posts.map(post => (
<li key={ posts.id }>
<h3>Title: { posts.title}</h3>
<p>Body: { posts.body }</p>
</li>
))}
Page 13 of 27
</ul>
)}
</div>
);
}
Page 14 of 27
4) Consider following code which desires to retrieves messages from the API endpoint. It is required
to fetch the messages only once when component is rendered. Complete the code to achieve
desired functionality. (10 Marks)
Write missing code to complete the functionality of the component. Specify the line number to insert
the code. Do not rewrite the complete code again and do not modify anything in existing code.
Note: It is an assumption that Insertion of the code will not effect the line numbers specified in the
given code. So, if you insert something on line number 5 will not bring rest of the code in next line.
useEffect(() => {
fetchMessages();
}, [])
Page 15 of 27
Insert Code at Line # 7
setMessages(data);
Page 16 of 27
5) Update the code provided in solution of above problem to fetch the messages from the server after
one second when component is rendered. (5 Marks)
setTimeout(() => {
fetchMessages()
}, 1000)
}, [])
return (
<ChildA user= { user } />
)
}
Page 17 of 27
const ChildB = (props) => {
return (
<ChildC user= { props.user } />
)
}
b) What is the issue with this approach, how it can be avoided? (5 Marks)
c) Re-write the code with the react prescribed approach to pass the props to the last component in the tree.
(5 Marks)
return (
<UserContext.Provider value={user}>
<ChildA />
</UserContext.Provider>
)
}
Page 18 of 27
return (
<ChildB />
)
}
Page 19 of 27
7) Consider a complex multi-level navigation structure in a React application using React Router. The
application consists of the following routes: (10 Marks)
Home ("/")
Products ("/products")
Product Details ("/products/:id")
Categories ("/categories")
Category Details ("/categories/:id")
Admin Dashboard ("/admin/dashboard")
Admin Products ("/admin/products")
Admin Categories ("/admin/categories")
Code a react router for the above pages. When coding React Router, group the Admin Routes.
Note: Assume that the pages/components already exist, you can assume any name for these
pages/components.
return (
<>
<Routes>
<Route path="/admin">
</Route>
</Routes>
</>
Page 20 of 27
);
Page 21 of 27
8) In a social media application, where a logged in user posts are stored in application level state. A
post has id, title and description.
a) Code a reducer which has an initial state, relevant actions for fetching and storing posts, and
exports (reducer and actions). (4 Marks)
// Actions
export const { fetch_posts } = postSlice.actions
Page 22 of 27
import store from './app/store'
import { Provider } from 'react-redux'
root.render(
<Provider store={store}>
<App />
</Provider>
)
useEffect(() => {
// Dispatch an action to fetch posts
dispatch(fetch_posts());
}, [posts]);
return (
<div>
<h1>Profile</h1>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
Page 23 of 27
<p>{post.description}</p>
</div>
))}
</div>
);
};
Page 24 of 27
Rough Work
Page 25 of 27
Rough Work
Page 26 of 27
Rough Work
Page 27 of 27