diff --git a/week-2/01-async-js/easy/counter.js b/week-2/01-async-js/easy/counter.js new file mode 100644 index 0000000000..ddf82eadd2 --- /dev/null +++ b/week-2/01-async-js/easy/counter.js @@ -0,0 +1,22 @@ +// ## Create a counter in JavaScript + +// We have already covered this in the second lesson, but as an easy recap try to code a counter in Javascript +// It should go up as time goes by in intervals of 1 second + +let count = 0; + +function counter(){ + setInterval(() =>{ + count++; + console.log(count); + }, 1000); +} + +function counter(){ + count++; + console.log(count); + + setTimeout(counter, 1000); +} +counter(); + diff --git a/week-2/01-async-js/easy/output.txt b/week-2/01-async-js/easy/output.txt new file mode 100644 index 0000000000..34b2fe2de1 --- /dev/null +++ b/week-2/01-async-js/easy/output.txt @@ -0,0 +1 @@ +wfwvvscsadwqfdqfd \ No newline at end of file diff --git a/week-2/01-async-js/easy/read-file-content.js b/week-2/01-async-js/easy/read-file-content.js new file mode 100644 index 0000000000..3f06be6cc0 --- /dev/null +++ b/week-2/01-async-js/easy/read-file-content.js @@ -0,0 +1,41 @@ +const fs = require ('fs').promises; +const prompt = require('prompt-sync')(); + +async function expensiveOperation(n){ + let res = 0; + for(let i = 0; i< n; i++){ + + res += Math.sqrt(i) * Math.random(); + } + + console.log(`Expensive computation result: ${res}`); +} +async function readFileContent(){ + + const FILE_PATH = "3-read-from-file.md"; + + try{ + const data = await fs.readFile(FILE_PATH, "utf-8"); + console.log("File Content: "); + console.log(data); + } + catch(err){ + console.error("Error Reading the file content: ", err.message); + } + +} + +async function main(){ + + const iterations = prompt('How Many Iterations? '); + console.log(`No of Iterations are , ${iterations}!`); + try{ + await Promise.all([readFileContent(), expensiveOperation(iterations)]); + } + catch(err){ + console.error('Program error:', error.message); + } + +} + +main(); diff --git a/week-2/01-async-js/easy/write-file-content.js b/week-2/01-async-js/easy/write-file-content.js new file mode 100644 index 0000000000..4b2bc8edf9 --- /dev/null +++ b/week-2/01-async-js/easy/write-file-content.js @@ -0,0 +1,48 @@ +const fs = require ('fs').promises; +const prompt = require('prompt-sync')(); + +async function expensiveOperation(n){ + let res = 0; + for(let i = 0; i< n; i++){ + + res += Math.sqrt(i) * Math.random(); + } + + console.log(`Expensive computation result: ${res}`); +} +async function writeFileContent(content){ + + const FILE_PATH = "output.txt"; + + try{ + await fs.writeFile(FILE_PATH, content, "utf-8"); + + console.log("Succesfully wrote to the file"); + + const data = await fs.readFile(FILE_PATH, "utf-8"); + console.log('File Content: '); + console.log(data); + } + catch(err){ + console.error("Error Writing to the file: ", err.message); + } + +} + +async function main() { + const content = prompt('Enter File Content to write to the file: '); + const iterations = parseInt(prompt('How Many Iterations? ')); + + try { + await Promise.all([ + writeFileContent(content), + expensiveOperation(iterations) + ]); + console.log('All operations completed successfully.'); + } catch (err) { + console.error('Program error:', err.message); + } + } + + +main(); diff --git a/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js b/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js index 32a99c83fc..07101aaa12 100644 --- a/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js +++ b/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js @@ -3,6 +3,21 @@ */ function wait(n) { + + return new Promise((resolve) =>{ + setTimeout(resolve, n * 1000); + }); } -module.exports = wait; + +async function main(){ + console.log('Start'); + + await wait(5); + + console.log('After 5 seconds'); +} + +main(); + +module.exports = wait; \ No newline at end of file diff --git a/week-2/01-async-js/hard (promises)/2-sleep-completely.js b/week-2/01-async-js/hard (promises)/2-sleep-completely.js index a171170b09..ecbbbad8d8 100644 --- a/week-2/01-async-js/hard (promises)/2-sleep-completely.js +++ b/week-2/01-async-js/hard (promises)/2-sleep-completely.js @@ -5,6 +5,25 @@ */ function sleep(milliseconds) { + + return new Promise((resolve) =>{ + // setTimeout(resolve, milliseconds); + // console.log('After resolve'); + + const start = Date.now(); + while(Date.now() - start < milliseconds){ + continue; + } + resolve(); + }) +} + +async function main(n){ + console.log('Before Sleep'); + await sleep(n); + console.log(`After Sleep for ${n} milliseconds`); + } +main(2000); module.exports = sleep; diff --git a/week-2/01-async-js/hard (promises)/3-promise-all.js b/week-2/01-async-js/hard (promises)/3-promise-all.js index a57838ade0..abffd6b073 100644 --- a/week-2/01-async-js/hard (promises)/3-promise-all.js +++ b/week-2/01-async-js/hard (promises)/3-promise-all.js @@ -5,19 +5,36 @@ */ function wait1(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait2(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait3(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } -function calculateTime(t1, t2, t3) { - +async function calculateTime(t1, t2, t3) { + const start = Date.now(); + return Promise.all([ + wait1(t1), + wait2(t2), + wait3(t3) + ]).then(() =>{ + const end = Date.now(); + return end - start; + }); } +calculateTime(1,2,3).then((time)=>{ + console.log(`Time Take: ${time} ms`); +}); module.exports = calculateTime; diff --git a/week-2/01-async-js/hard (promises)/4-promise-chain.js b/week-2/01-async-js/hard (promises)/4-promise-chain.js index 6044e241f7..9d71529733 100644 --- a/week-2/01-async-js/hard (promises)/4-promise-chain.js +++ b/week-2/01-async-js/hard (promises)/4-promise-chain.js @@ -5,20 +5,38 @@ * Compare it with the results from 3-promise-all.js */ -function wait1(t) { +function wait1(t) { + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait2(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait3(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function calculateTime(t1, t2, t3) { + const start = Date.now(); + return wait1(t1) + .then(() => wait2(t2) + .then(() =>wait3(t3) + .then(() =>{ + const end = Date.now(); + return end - start; + }))); } - +calculateTime(1,2,3) +.then((time)=>{ + console.log(`Time taken: ${time}`); +}); module.exports = calculateTime; diff --git a/week-2/01-async-js/medium/clock.js b/week-2/01-async-js/medium/clock.js new file mode 100644 index 0000000000..e5e1f9f4ac --- /dev/null +++ b/week-2/01-async-js/medium/clock.js @@ -0,0 +1,18 @@ +function updateClock() { + const now = new Date(); + + // Format for 24-hour time (HH:MM:SS) + const time24 = now.toTimeString().split(' ')[0]; + + // Format for 12-hour time (HH:MM:SS AM/PM) + const time12 = now.toLocaleTimeString('en-US', { + hour12: true, + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }); + + setTimeout(updateClock, 1000); +} + +updateClock(); diff --git a/week-2/01-async-js/medium/file-cleaner.js b/week-2/01-async-js/medium/file-cleaner.js new file mode 100644 index 0000000000..f8d1bda9d9 --- /dev/null +++ b/week-2/01-async-js/medium/file-cleaner.js @@ -0,0 +1,37 @@ +// ## File cleaner +// Read a file, remove all the extra spaces and write it back to the same file. + +// For example, if the file input was +// ``` +// hello world my name is raman +// ``` + +// After the program runs, the output should be + +// ``` +// hello world my name is raman +// ``` + + +const fs = require('fs').promises; + +const FILE_PATH = 'file-cleaner.txt'; + +async function cleanContent(filepath){ + try{ + const data = await fs.readFile(filepath, 'utf-8'); + const replacedContent = data.replace(/\s+/g, ' ').trim(); + await fs.writeFile(filepath, replacedContent); + + console.log('File Content Has Been Cleaned !!'); + + const newData = await fs.readFile(filepath, 'utf-8'); + console.log('New Content of the File: '); + console.log(newData); + } + catch(err){ + console.error('Error Processing the file: ', err.message); + } +} + +cleanContent(FILE_PATH); \ No newline at end of file diff --git a/week-2/01-async-js/medium/file-cleaner.txt b/week-2/01-async-js/medium/file-cleaner.txt new file mode 100644 index 0000000000..1a2e9e6283 --- /dev/null +++ b/week-2/01-async-js/medium/file-cleaner.txt @@ -0,0 +1 @@ +hello this is a sample text that needs to be cleaned \ No newline at end of file diff --git a/week-2/02-nodejs/todoServer.js b/week-2/02-nodejs/todoServer.js index 4b55de9f9e..d0c459e263 100644 --- a/week-2/02-nodejs/todoServer.js +++ b/week-2/02-nodejs/todoServer.js @@ -1,49 +1,123 @@ -/** - You need to create an express HTTP server in Node.js which will handle the logic of a todo list app. - - Don't use any database, just store all the data in an array to store the todo list data (in-memory) - - Hard todo: Try to save responses in files, so that even if u exit the app and run it again, the data remains (similar to databases) - - Each todo has a title and a description. The title is a string and the description is a string. - Each todo should also get an unique autogenerated id every time it is created - The expected API endpoints are defined below, - 1.GET /todos - Retrieve all todo items - Description: Returns a list of all todo items. - Response: 200 OK with an array of todo items in JSON format. - Example: GET http://localhost:3000/todos - - 2.GET /todos/:id - Retrieve a specific todo item by ID - Description: Returns a specific todo item identified by its ID. - Response: 200 OK with the todo item in JSON format if found, or 404 Not Found if not found. - Example: GET http://localhost:3000/todos/123 - - 3. POST /todos - Create a new todo item - Description: Creates a new todo item. - Request Body: JSON object representing the todo item. - Response: 201 Created with the ID of the created todo item in JSON format. eg: {id: 1} - Example: POST http://localhost:3000/todos - Request Body: { "title": "Buy groceries", "completed": false, description: "I should buy groceries" } - - 4. PUT /todos/:id - Update an existing todo item by ID - Description: Updates an existing todo item identified by its ID. - Request Body: JSON object representing the updated todo item. - Response: 200 OK if the todo item was found and updated, or 404 Not Found if not found. - Example: PUT http://localhost:3000/todos/123 - Request Body: { "title": "Buy groceries", "completed": true } - - 5. DELETE /todos/:id - Delete a todo item by ID - Description: Deletes a todo item identified by its ID. - Response: 200 OK if the todo item was found and deleted, or 404 Not Found if not found. - Example: DELETE http://localhost:3000/todos/123 - - - For any other route not defined in the server return 404 - - Testing the server - run `npm run test-todoServer` command in terminal - */ - const express = require('express'); - const bodyParser = require('body-parser'); - - const app = express(); - - app.use(bodyParser.json()); - - module.exports = app; \ No newline at end of file +const express = require('express'); +const fs = require('fs').promises; +const app = express(); +const path = require('path'); +app.use(express.json()); + +const TODOS_FILE_PATH = path.join(__dirname, 'todos.json'); + +async function readTodos() { + try { + const data = await fs.readFile(TODOS_FILE_PATH, 'utf-8'); + return JSON.parse(data); + } catch (err) { + if (err.code === 'ENOENT') { + return []; + } + throw err; + } +} + + +async function writeTodos(todos) { + try { + await fs.writeFile(TODOS_FILE_PATH, JSON.stringify(todos, null, 2)); + } catch (err) { + console.error('Error writing todos:', err); + throw err; + } +} + +app.get("/todos", async function (req, res) { + + todos = await readTodos(); + res.status(200).json(todos) +}); + +app.get("/todos/:id", async function (req, res) { + try { + const todoID = parseInt(req.params.id); + const todos = await readTodos(); + const todo = todos.find(t => t.id === todoID); + + if (!todo) { + return res.status(404).json({ message: `Todo not found for id ${todoID}` }); + } + + res.status(200).json(todo); + } catch (err) { + res.status(500).json({ message: 'Internal server error' }); + } +}); + +app.post('/todos', async function (req, res) { + const todo = req.body; + + if (!todo['title'] || !todo['description']) { + return res.status(400).json({ message: 'Title and description are required' }); + } + + const todos = await readTodos(); + + let maxID = todos.length > 0 ? Math.max(...todos.map(t => t.id)) : 0; + const newTodo = { + id: maxID + 1, + title: todo['title'], + description: todo['description'], + completed: todo['completed'] + }; + todos.push(newTodo); + await writeTodos(todos); + + res.status(201).json({ id: newTodo.id }); + +}); + +app.delete('/todos/:id', async function (req, res) { + const todos = await readTodos(); + const id = parseInt(req.params.id); + const todoIndex = todos.findIndex(t => t.id === id); + + if (todoIndex === -1) { + return res.status(404).json({ message: 'requested id not found' }); + } + + todos.splice(todoIndex, 1); + await writeTodos(todos); + res.status(200).json({ message: 'Todo deleted successfully' }); +}); + +app.put('/todos/:id', async function (req, res) { + const id = parseInt(req.params.id); + const { title, description, completed } = req.body; + const todos = await readTodos(); + const todoIndex = todos.findIndex(t => t.id === id); + + if (todoIndex === -1) { + return res.status(404).json({ message: 'requested id not found' }); + } + + todos[todoIndex] = { + ...todos[todoIndex], + title: title || todos[todoIndex].title, + description: description || todos[todoIndex].description, + completed: completed !== undefined ? completed : todos[todoIndex].completed + }; + + await writeTodos(todos); + res.status(200).json(todos[todoIndex]); +}); + + +const PORT = 3000; + +app.listen(PORT, () => { + console.log(`App listening on port ${PORT}!`); +}); +function startServer(port) { + return app.listen(port, () => { + console.log(`App listening on port ${port}!`); + }); +} + +module.exports = { app, startServer }; diff --git a/week-3/01-middlewares/01-requestcount.js b/week-3/01-middlewares/01-requestcount.js index aced495488..65576a76c4 100644 --- a/week-3/01-middlewares/01-requestcount.js +++ b/week-3/01-middlewares/01-requestcount.js @@ -1,15 +1,24 @@ const request = require('supertest'); const assert = require('assert'); const express = require('express'); +const { futimesSync } = require('fs'); const app = express(); let requestCount = 0; +app.use(express.json()); // You have been given an express server which has a few endpoints. // Your task is to create a global middleware (app.use) which will // maintain a count of the number of requests made to the server in the global // requestCount variable +function requestCounter(req, res, next){ + requestCount++; + next(); +} + +app.use(requestCounter); + app.get('/user', function(req, res) { res.status(200).json({ name: 'john' }); }); @@ -22,4 +31,8 @@ app.get('/requestCount', function(req, res) { res.status(200).json({ requestCount }); }); +app.listen(3001, () =>{ + console.log('server is running on port 3000'); +}); + module.exports = app; \ No newline at end of file diff --git a/week-3/01-middlewares/02-ratelimitter.js b/week-3/01-middlewares/02-ratelimitter.js index 3329bb9497..d0a16dd707 100644 --- a/week-3/01-middlewares/02-ratelimitter.js +++ b/week-3/01-middlewares/02-ratelimitter.js @@ -13,9 +13,32 @@ const app = express(); let numberOfRequestsForUser = {}; setInterval(() => { - numberOfRequestsForUser = {}; + numberOfRequestsForUser = {}; }, 1000) +app.use(express.json()); + +function rateLimiter(req, res, next){ + const userID = req.headers['user-id']; + // if(!userID){ + // return res.status(400).json({err: 'Missing user-id header'}); + // } + if(!numberOfRequestsForUser[userID]){ + numberOfRequestsForUser[userID] = 1; + } + else{ + numberOfRequestsForUser[userID]++; + } + if(numberOfRequestsForUser[userID] > 5){ + return res.status(404) + .set('Retry-After', '1') + .json({err: 'Too Many Requests'}); + } + next(); +} + +app.use(rateLimiter); + app.get('/user', function(req, res) { res.status(200).json({ name: 'john' }); }); @@ -24,4 +47,8 @@ app.post('/user', function(req, res) { res.status(200).json({ msg: 'created dummy user' }); }); +app.listen(3002, () =>{ + console.log('server is running on port 3000'); +}) + module.exports = app; \ No newline at end of file diff --git a/week-3/01-middlewares/03-errorcount.js b/week-3/01-middlewares/03-errorcount.js index c5374ae6ef..cf03c51c56 100644 --- a/week-3/01-middlewares/03-errorcount.js +++ b/week-3/01-middlewares/03-errorcount.js @@ -23,4 +23,14 @@ app.get('/errorCount', function(req, res) { res.status(200).json({ errorCount }); }); +app.use((err,req,res,next) =>{ + errorCount++; + res.status(404) + .json({err: 'Not Found'}); +}); + +app.listen(3000, () =>{ + console.log('server is running on port 3000'); +}); + module.exports = app; \ No newline at end of file diff --git a/week-3/02-jwt/index.js b/week-3/02-jwt/index.js index fb7c604c81..c13233507e 100644 --- a/week-3/02-jwt/index.js +++ b/week-3/02-jwt/index.js @@ -1,6 +1,9 @@ const jwt = require('jsonwebtoken'); const jwtPassword = 'secret'; +const zod = require('zod'); +const emailSchema = zod.string().email(); +const passwordSchema = zod.string().min(6, {message: 'Password must be at least 6 characters long'}); /** * Generates a JWT for a given username and password. @@ -15,6 +18,18 @@ const jwtPassword = 'secret'; */ function signJwt(username, password) { // Your code here + const emailValidation = emailSchema.safeParse(username); + const passwordValidation = passwordSchema.safeParse(password); + if(emailValidation.success && passwordValidation.success){ + const payload = {username, password}; + // const options = { expiresIn: '5h' }; // Token expiration time + // const token = jwt.sign(payload, jwtPassword, options); + const token = jwt.sign(payload, jwtPassword); + return token; + } + else{ + return null; + } } /** @@ -27,6 +42,13 @@ function signJwt(username, password) { */ function verifyJwt(token) { // Your code here + try{ + const decoded = jwt.verify(token, jwtPassword); + return true; + } + catch(err){ + return false; + } } /** @@ -37,7 +59,18 @@ function verifyJwt(token) { * Returns false if the token is not a valid JWT format. */ function decodeJwt(token) { - // Your code here + try{ + const decoded = jwt.decode(token); + if(decoded){ + return true; + } + else{ + return false; + } + } + catch(err){ + return false; + } } diff --git a/week-5/level-1/BusinessCardReactApp/src/CardComponent,jsx b/week-5/level-1/BusinessCardReactApp/src/CardComponent,jsx new file mode 100644 index 0000000000..efb21e9e63 --- /dev/null +++ b/week-5/level-1/BusinessCardReactApp/src/CardComponent,jsx @@ -0,0 +1,41 @@ +// Card Component: + +// Name +// Desc +// Social Media +// Interests + +import React from 'react'; +import './Card.css'; + +const Card = ({person}) =>{ + const {name, desc, socialMedia, interests} = person; + return( +
+
+

{name}

+
+
+

{desc}

+
+ {socialMedia.linkedin && ( + LinkedIn + )} + {socialMedia.twitter && ( + Twitter + )} +
+
+

Interests

+
+ {interests.map((interest, index) => ( +
{interest}
+ ))} +
+
+
+
+ ) +} + +export default Card; \ No newline at end of file diff --git a/week-6/1-use-memo/src/components/Assignment1.jsx b/week-6/1-use-memo/src/components/Assignment1.jsx index edce8706e8..d529411de4 100644 --- a/week-6/1-use-memo/src/components/Assignment1.jsx +++ b/week-6/1-use-memo/src/components/Assignment1.jsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useState, useMemo } from "react"; // In this assignment, your task is to create a component that performs an expensive calculation (finding the factorial) based on a user input. // Use useMemo to ensure that the calculation is only recomputed when the input changes, not on every render. @@ -6,7 +6,17 @@ import { useState } from "react"; export function Assignment1() { const [input, setInput] = useState(0); // Your solution starts here - const expensiveValue = 0; + + const expensiveValue = useMemo(() => { + + if(input <= 1) return 1; + let res = 1; + for(let i = 1; i<= input; i++){ + res*= i; + } + return res; + }, [input]); + // Your solution ends here return ( diff --git a/week-6/1-use-memo/src/components/Assignment2.jsx b/week-6/1-use-memo/src/components/Assignment2.jsx index 5b3abe0462..4d2c29a1cc 100644 --- a/week-6/1-use-memo/src/components/Assignment2.jsx +++ b/week-6/1-use-memo/src/components/Assignment2.jsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useState, useMemo} from "react"; // In this assignment, you will create a component that renders a large list of sentences and includes an input field for filtering these items. // The goal is to use useMemo to optimize the filtering process, ensuring the list is only re-calculated when necessary (e.g., when the filter criteria changes). @@ -20,13 +20,16 @@ export function Assignment2() { const [sentences, setSentences] = useState(ALL_WORDS); const [filter, setFilter] = useState(""); - const filteredSentences = sentences.filter(x => x.includes(filter)) + const filteredSentences = useMemo(() =>{ + return sentences.filter(x => x.includes(filter)); + }, [filter, sentences]); return
{ setFilter(e.target.value) - }}> - {filteredSentences.map(word =>
+ }} + /> + {filteredSentences.map((word, index) =>
{word}
)}
diff --git a/week-6/1-use-memo/src/components/Assignment3.jsx b/week-6/1-use-memo/src/components/Assignment3.jsx index 7d2b4caae4..241e3394ec 100644 --- a/week-6/1-use-memo/src/components/Assignment3.jsx +++ b/week-6/1-use-memo/src/components/Assignment3.jsx @@ -8,11 +8,17 @@ export const Assignment3 = () => { { name: 'Chips', value: 20 }, { name: 'Onion', value: 30 }, { name: 'Tomato', value: 30 }, + { name: 'aalu', value: 30 }, + { name: 'ginger', value: 50}, + { name: 'grapes', value: 30 }, + { name: 'gobhi', value: 30 }, // Add more items as needed ]); // Your code starts here - const totalValue = 0; + const totalValue = useMemo(() =>{ + return items.reduce((acc, item) => acc + item.value, 0); + }, [items]); // Your code ends here return (
diff --git a/week-6/2-use-callback/src/components/Assignment1.jsx b/week-6/2-use-callback/src/components/Assignment1.jsx index 23c4e54ed2..fbecc5d5ee 100644 --- a/week-6/2-use-callback/src/components/Assignment1.jsx +++ b/week-6/2-use-callback/src/components/Assignment1.jsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import React, { useState, useCallback, memo} from "react"; // Create a counter component with increment and decrement functions. Pass these functions to a child component which has buttons to perform the increment and decrement actions. Use useCallback to ensure that these functions are not recreated on every render. @@ -6,15 +6,14 @@ export function Assignment1() { const [count, setCount] = useState(0); // Your code starts here - function handleIncrement() { + const handleIncrement = useCallback(() =>{ + setCount((count) => count + 1); + }, []); - } - - function handleDecrement() { - - } + const handleDecrement = useCallback(() =>{ + setCount((count) => count - 1); + }, []); // Your code ends here - return (

Count: {count}

@@ -23,9 +22,9 @@ export function Assignment1() { ); }; -const CounterButtons = ({ onIncrement, onDecrement }) => ( +const CounterButtons = memo(({ onIncrement, onDecrement }) => (
-); +)); diff --git a/week-6/2-use-callback/src/components/Assignment2.jsx b/week-6/2-use-callback/src/components/Assignment2.jsx index 606ca8a21b..8321d2efb6 100644 --- a/week-6/2-use-callback/src/components/Assignment2.jsx +++ b/week-6/2-use-callback/src/components/Assignment2.jsx @@ -8,9 +8,9 @@ export function Assignment2() { const [inputText, setInputText] = useState(''); // Your code starts here - function showAlert() { - - } + const showAlert = useCallback(()=>{ + alert(inputText); + }, [inputText]); // Your code ends here return ( diff --git a/week-6/3-use-ref/src/App.jsx b/week-6/3-use-ref/src/App.jsx index 286d2474fe..122ce66cee 100644 --- a/week-6/3-use-ref/src/App.jsx +++ b/week-6/3-use-ref/src/App.jsx @@ -6,7 +6,7 @@ function App() { return ( <> - {/* */} + ) } diff --git a/week-6/3-use-ref/src/components/Assignment1.jsx b/week-6/3-use-ref/src/components/Assignment1.jsx index 66a0f7c5f5..3ccf75f5db 100644 --- a/week-6/3-use-ref/src/components/Assignment1.jsx +++ b/week-6/3-use-ref/src/components/Assignment1.jsx @@ -1,20 +1,23 @@ -import { useEffect } from "react"; +import { useEffect, useRef } from "react"; // Create a component with a text input field and a button. When the component mounts or the button is clicked, automatically focus the text input field using useRef. export function Assignment1() { - + const inputRef = useRef(null); useEffect(() => { - + inputRef.current.focus(); }, []); const handleButtonClick = () => { - + inputRef.current.focus(); }; return (
- +
); diff --git a/week-6/3-use-ref/src/components/Assignment2.jsx b/week-6/3-use-ref/src/components/Assignment2.jsx index 2831959dc4..effd8ccad6 100644 --- a/week-6/3-use-ref/src/components/Assignment2.jsx +++ b/week-6/3-use-ref/src/components/Assignment2.jsx @@ -1,18 +1,22 @@ -import React, { useState, useCallback } from 'react'; +import React, { memo, useState, useCallback, useRef} from 'react'; +import { useEffect } from 'react'; // Create a component that tracks and displays the number of times it has been rendered. Use useRef to create a variable that persists across renders without causing additional renders when it changes. export function Assignment2() { - const [, forceRender] = useState(0); - + const [count, setCount] = useState(0); + const numberOfTimesReRendered = useRef(0); + useEffect(() =>{ + numberOfTimesReRendered.current += 1; + }) const handleReRender = () => { // Update state to force re-render - forceRender(Math.random()); + // setForceRender(Math.random()); + setCount(count + 1); }; - return (
-

This component has rendered {0} times.

+

This component has rendered {numberOfTimesReRendered.current} times.

);