Problems encountered with MongoDB and webpack 5

I’m trying to work with MongoDB and React.js but I have problems with MongoDB dependencies.

package.json/dependencies :

"dependencies": {
"dotenv": "^16.3.1",
"mongodb": "^4.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.10.1",
"react-scripts": "^5.0.1",
"sass": "^1.64.1",
"webpack": "^5.88.2"
},

and the two kind of errors I get (about 60 repetitions for the first one and 10 for the second one) :

ERROR in ./node_modules/whatwg-url/dist/encoding.js 6:4-19
Module not found: Error: Can't resolve 'util' in 'D:DocumentsDev_Projectsproto-busnode_moduleswhatwg-urldist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

second one :

ERROR in ./node_modules/mongodb/lib/cmap/auth/mongocr.js 7:15-32
Module not found: Error: Can't resolve 'crypto' in 'D:DocumentsDev_Projectsproto-busnode_modulesmongodblibcmapauth'

The first error concerning polyfill and webpack can be resolved by adding a fallback and installing the npm package, but the second cannot.

I found information on the internet about compatibility issues between Web3 and Webpack 5, but downgrading the packages didn’t work ([email protected] and [email protected]). So I think there’s an easier way of solving this problem than manually adding fallbacks.

Another possibility is that MongoDB can’t work with react, and needs an express server.

Thanks in advance for your help.

Web-Development Templates (html, css, js)

I am a beginner in web development and I want to make a basic layout for all my pages.
So i created a basic page layout with these files.

  • Template.html (which links to the Template.css and Template.js files)
  • Template.css
  • Template.js

Each Page should include the Template and add the content into a specific location (maybe a empty container inside the Template)

  • Page1.html
  • Page1.css
  • Page1.js

But I dont know how to link the Template and the Pages.
If anyone has a simple example how to solve this, it would be nice. Thanks

It would be cool, where I have an approach where I can reuse the content of the template in the corresponding pages

Getting YouTube embed videos to target an iframe on another url on my site

My homepage displays thumbnails of youtube game videos, e.g

[game1_vid1] [game1_vid2] [game2_vid1]

They currently open and play in a modal window when clicked on.

However, each game has its own page, e.g mysite.com/game1/

On that page (/game1) there is a iframe (iframe_main), and below that you will also find the thumbs for that game. So when someone clicks [game1_vid2], that vid will play in iframe_main, which is on the same game page.

However, I want users to be able to click on the thumbs on the homepage, and for the video to open in iframe_main on the relevant games page.

E.g so when someone clicks on [game1_vid2] on the homepage, the video will target the mysite.com/game1/ url, and also target iframe_main on the url.

What is the best way to achieve this?

Here is the code of the iframe_main –

<div class="iframe-container2" style="margin-bottom:0px;"><iframe width="560" height="315" src="https://www.youtube.com/embed/'.$video->YouTubeID.'?controls=1&amp;showinfo=0&amp;rel=0" frameborder="0" allowfullscreen="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="iframe_main">

and the thumbs –

<a onclick="scrollWin()" href="/modal2/video/'.urlencode($video->YouTubeID).'"  target="iframe_main" >

The above works great, but the thumbs are on the same url, so they just target the iframe on the same page. However now I want to make the thumbs on the homepage target iframe_main, when clicked on.

I hope that all makes sense. Thanks for any help.
Chris

Issue with codewars js task

This is my code task:

In this simple exercise, you will build a program that takes a value, integer , and returns a list of its multiples up to another value, limit . If limit is a multiple of integer, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base.

For example, if the parameters passed are (2, 6), the function should return [2, 4, 6] as 2, 4, and 6 are the multiples of 2 up to 6.

const arr=[];

function findMultiples(integer, limit) {
  //your code here
  if (integer < limit && integer > 0){
    if(limit % integer === 0){
    let tempResult = limit / integer;
    for (let i=1; i < tempResult + 1; i++){
     arr.push(i * integer);
    }
    }else if (limit % integer !== 0){
    let calcRemainder = limit % integer;
    let result = (limit - calcRemainder) / integer;
    for (let i=1; i < result + 1; i++){
     arr.push(i * integer);
    }
    }
    console.log(arr)
    }else {
      console.log('invalid input')
      return ''
    }
  
}
findMultiples(4, 19)

And this is the test result:

Test Results:
Log
[ 4, 8, 12, 16 ]
Tests
Basic Tests
Log
[
4, 8, 12, 16, 5,
10, 15, 20, 25
]
expected undefined to be an array
Completed in 3ms
Random Tests
Log
[
4, 8, 12, 16, 5, 10, 15,
20, 25, 1, 2, 3, 4, 5,
6, 7, 8
]
Testing for integer=1 and limit=8: expected undefined to be an array.

I don’t understand why codewars don’t accept my code. The strange thing for me is when codewars tests my code it returns always an array with the elements 5,10,15,20,25. What am i doing wrong ?

Thanks in advance

How to add icon to WooCommerce add to cart button

in woocommerce, I want to add an icon from the iconify library to the add to cart button of my site
I made some attempts, but I did not get the desired result.
I used WooCommerce hooks, but this icon is displayed as an html tag and does not work,this code is:

add_filter('woocommerce_product_single_add_to_cart_text', 'ChangeAddToCartBtnText');
add_filter('woocommerce_product_add_to_cart_text', 'ChangeAddToCartBtnText');
function ChangeAddToCartBtnText()
{
    $ProductID = get_the_ID();
    $Stock = get_post_meta($ProductID, '_stock_status', true);
    if ($Stock == 'outofstock') {
        $text = '<iconify-icon icon="fluent:info-12-regular"></iconify-icon> More Info';
    } else {
        $text = '<iconify-icon icon="fluent:cart-24-regular"></iconify-icon>  Add To cart';
    }
    return $text;
    //You can also do this with switch statement
}

I decided to do this with jquery, but I ran into problems at this stage, my code is this:

 $('#primary .button ').html('<iconify-icon icon="fluent:info-12-regular"></iconify-icon> More Info');
    $('#primary .add_to_cart_button ').html('<iconify-icon icon="fluent:cart-24-regular"></iconify-icon> Add To cart');

But this code is only responsive when the page is opened for the first time, and when the user uses ajax filters, the shopping cart buttons return to their original state without icons.
I tried to run this code when the structure of the category page changes when a filter is selected and the products are rearranged, my code is:

 var typingTimer;                //timer identifier
    var doneTypingInterval = 1000;  //time in ms, 5 seconds for example
    var $input = $('#primary');
    var Products, LastLength;
    //on keyup, start the countdown
    $input.one('DOMSubtreeModified', function () {
        Products = $('[id^=ProductBox_]');
        if (Products.length == LastLength && Products.length != 0) {
        } else {
            LastLength = Products.length;
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        }
    });
    //user is "finished typing," do something
    function doneTyping() {
        $('#primary .button ').html('<iconify-icon icon="fluent:info-12-regular"></iconify-icon> More Info');
        $('#primary .add_to_cart_button ').html('<iconify-icon icon="fluent:cart-24-regular"></iconify-icon>  Add To cart');
    }

But this code only works once, that is, if the user selects two filters, the buttons will return to the first state.
Even I from $input.bind('DOMSubtreeModified', function () { I also used it, but this also creates unnecessary processing for the site, and this slows down my product category page, this code causes my function to run indefinitely, and this is not good at all.

FFmpeg percentage progress in javascript

I use javascript, Vue 3 and FFmpeg version:

"@ffmpeg/core": "^0.11.0",
"@ffmpeg/ffmpeg": "^0.11.6",

I have a function that cuts videos based on times entered by the user:

async videoTrim() {
  this.ffmpeg.FS("writeFile", "video.mp4", await fetchFile(videoData.source));

  await this.ffmpeg.run(
    "-ss", startTime,
    "-i", "video.mp4",
    "-to", endTime,
    "-crf", "23",
    "-c:v", "copy",
    "-c:a", "copy",
    "-reset_timestamps", "1",
    "-avoid_negative_ts", "1",
    "videoNew.mp4",
  )

  return this.ffmpeg.FS("readFile", "videoNew.mp4");
}

PROBLEM:
I need to find out the percentage progress during video trimming so that I can give the user information about how long the trimming will take
(If you have any comments or suggestions for improving the function this.ffmpeg.run, please let me know)

Catching the json message returned from the catch with ajax

An error message is returned from the catch with json.I want to show this message but I can’t seem to catch it.

Controller :

 public ActionResult GetTable()
        {
            try
            {
               ...
            }
            catch (Exception ex)
            {
               ........
                return Json(new { result = false, message = "İşlem başarıyla gerçekleşti ancak tablo güncellenirken bir sorun oluştu." });
            }
        }

Js :

function updateTable(isInsert) {
    var pageNumber = 1;
    if (isInsert) {
        pageNumber = 1;
    } else {
        pageNumber = $('#customersTable').bootstrapTable('getOptions').pageNumber;
    }
    $.get('/Customer/GetTable', function (data) {
        $('#tableContainer').html(data);
        $('#customersTable').bootstrapTable('destroy');
        $('#customersTable').bootstrapTable();
        $('#customersTable').bootstrapTable('selectPage', pageNumber);
    })
        .fail(function (jqXHR, textStatus, errorThrown) {
            var response = jqXHR.responseText;
            showToast('Başarısız', response.message, false);
        });
}

“React.js Components Not Re-Rendering After State Updates: Troubleshooting Tips?”

“I’m encountering an issue with React.js where my components are not re-rendering after state updates. I’ve checked my code, and it seems fine. What are some common reasons for components not re-rendering in React, and how can I troubleshoot this problem effectively?”

“I’ve been working on a React.js project, and I’ve encountered an issue where my components are not re-rendering after state updates. To resolve this, I first checked for any errors in the console and reviewed my component code for any issues. I also made sure that I’m using the correct lifecycle methods. However, none of these steps have resolved the issue. My expectation is that the components should re-render when the state changes, but that’s not happening. What else should I try to troubleshoot this problem effectively?”

JavaScript Role Based Access Failed

Very New to backend development and decided to use Node.JS as my backend due to already having experience with front end JS, i am at a loss on how i can accomplish Role based access.

I want the code to block any users that are not logged in from accessing anything other than the log in and signup page as well as preventing the user without the proper role to access certain things.

here is my front end login JS:

    // Wait for the DOM to load
if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready);
} else {
    ready();
}

function ready() {
    const loginpassword = document.getElementById('loginpassword');
    const togglePasswordButton = document.getElementById('ShowPass');

    togglePasswordButton.addEventListener('click', function () {
        if (loginpassword.type === 'password') {
            loginpassword.type = 'text';
        } else {
            loginpassword.type = 'password';
            togglePasswordButton.textContent = 'Show Password';
        }
    });

    // Add event listener to the Login button
    const loginButton = document.getElementById('Login');

    loginButton.addEventListener('click', () => {
        const username = document.getElementById('loginuser').value;
        const password = document.getElementById('loginpassword').value;

        // Validate user input
        if (!username || !password) {
            alert('Please enter your username and password.');
            return;
        }

        // Create an object with login data
        const loginData = {
            username,
            password,
        };

        // Send a POST request to the backend login route
        fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(loginData),
        })
            .then((response) => response.json())
            .then((data) => {
                if (data.error) {
                    // Display an error alert if login fails
                    alert('Login failed. Please check your username and password.');
                } else {
                    // Store the token securely in localStorage
                    localStorage.setItem('authToken', data.token);
                    
                    // Determine where to redirect based on user's access
                    if (data.access === 'teacher') {
                        window.location.href = '../Teacher-Pages/T-Home.html'; // Teacher dashboard URL
                    } else if (data.access === 'student') {
                        window.location.href = '../Student-Pages/S-Home.html'; // Student dashboard URL
                    } else {
                        alert('Invalid user access.'); // Handle other access types as needed
                    }
                }
            })
            .catch((error) => {
                console.error(error); // Log the error for debugging
                alert('An error occurred during the login process.');
            });
    });
}

Here a token i set when the user logs in

// NPM Packages used
const express = require('express'); // Node Framework For Web Apps
const router = express.Router(); // Express to export this route as a router fetchables by front end
const mysql = require('mysql'); // NPM Package For Using MySQL
const bodyParser = require('body-parser'); // NPM Package that enables backend to parse user inputs as json
const bcrypt = require('bcrypt'); // NPM Package used to encrypt passwords
const jwt = require('jsonwebtoken'); // NPM Package for creating session tokens

const connection = require('../database/connector');
const config = require('../Misc/Config');

router.use(bodyParser.json());

// Define the login route
router.post('/login', (req, res) => {
    const { username, password } = req.body;

    // Check if the username and password are provided
    if (!username || !password) {
        res.status(400).json({ error: 'Username and password are required.' });
        return;
    }

    // Query the database to find the user by username
    const sql = 'SELECT * FROM accounts.loginfo WHERE username = ?';
    connection.query(sql, [username], async (error, results) => {
        if (error) {
            console.error(error);
            res.status(500).json({ error: 'An error occurred during login.' });
        } else {
            // Check if the user exists
            if (results.length === 0) {
                res.status(401).json({ error: 'Invalid username or password.' });
            } else {
                // Verify the password
                const user = results[0];
                const passwordMatch = await bcrypt.compare(password, user.password);

                if (!passwordMatch) {
                    res.status(401).json({ error: 'Invalid username or password.' });
                } else {
                    // User is authenticated; create a JWT token with the user's role
                    const token = generateAuthToken(user);

                    // Include the user's role in the response
                    res.status(200).json({ token, access: user.access });
                }
            }
        }
    });
});

// Function to generate a JWT token with user role
function generateAuthToken(user) {
    // Include user data and role in the JWT token payload
    const token = jwt.sign({ userId: user.id, username: user.username, role: user.access }, config.secretKey, { expiresIn: '2h' });
    return token;
}

module.exports = router;

(ignore some of the comments, its for documentation)
Here on the backend route i add some info to the token regarding who logged in

// authentication.js

const jwt = require('jsonwebtoken');
const config = require('../Misc/Config');

function authenticateToken(requiredRole) {
    return (req, res, next) => {
        const token = req.headers.authorization;

        if (!token) {
            return res.status(401).json({ error: 'Authentication token is missing.' });
        }

        jwt.verify(token, config.secretKey, (err, user) => {
            if (err) {
                return res.status(403).json({ error: 'Invalid token.' });
            }

            if (user.access !== requiredRole) {
                return res.status(403).json({ error: 'Access denied. Insufficient privileges.' });
            }

            req.user = user;
            next();
        });
    };
}

module.exports = authenticateToken;

Here i tried to add a authentication function by the using tokens. (but in my case they don’t work because despite not being logged in and just tampering with the url i am able to access the pages only those logged in should have access to)

// student-homepage.js

// Wait for the DOM to load
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', setup);
} else {
    setup();
}

function setup() {
    const logoutButton = document.getElementById('Logout');

    logoutButton.addEventListener('click', () => {
        const authToken = localStorage.getItem('authToken');

        if (!authToken) {
            window.location.href = '../Universal-Pages/LogIn.html';
        } else {
            fetch('/api/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
                .then((response) => {
                    if (response.ok) {
                        localStorage.removeItem('authToken');
                        window.location.href = '../Universal-Pages/LogIn.html';
                        alert('Successfully Logged Out');
                    } else {
                        alert('Logout failed. Please try again.');
                    }
                })
                .catch((error) => {
                    console.error(error);
                    alert('An error occurred during the logout process.');
                });
        }

        // Decode the token to get user's role
        const decodedToken = jwt_decode(authToken);
        const userRole = decodedToken.access;

        if (userRole !== 'student') {
            window.location.href = '../Universal-Pages/AccessDenied.html';
        }
    });
}

Here for example for the front end script of the student homepage i have some code that should verify if the user is a student based on their token but in my case they dont work, this code is also supposed to work in conjuction with the following:

const express = require('express');
const router = express.Router();
const authenticateToken = require('./authentication');

// Protected teacher homepage route
router.get('/student-home', authenticateToken('student'), (req, res) => {
    res.sendFile('../public/Student-Pages/S-Home.html');
});

module.exports = router;

i have an inkling that i may have done something wrong here thats why i am asking for your help to solve my predicament.

Here is My main app.js if its necessary:

// NPM packages used
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const config = require('./Misc/Config');

// Import the necessary routes
const signupRoute = require('./routes/signup');
const loginRoute = require('./routes/login');
const logoutRoute = require('./routes/logout');
const authFunction = require('./routes/authentication');
const studentRoute = require('./routes/student');
const teacherRoute = require('./routes/teacher');

// Serve static files from the 'public' directory
app.use(express.static('public'));

// Middleware to parse incoming JSON data
app.use(bodyParser.json());

// api prefixes
app.use('/api', signupRoute);
app.use('/api', loginRoute);
app.use('/api', logoutRoute);
app.use('/api', studentRoute);
app.use('/api', teacherRoute);
app.use('/func', authFunction);


// Start the server
const port = process.env.PORT || 3002;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Here is also my File Structure:

File Structure

Again im am very new to full stack web development and is in need of how i can implement the role based access system and preventing people who arent logged in the first place to access the pages via tampering with the url, i know the question is quite cumbersome but i thank anyone who could help. i can provide more information or code if needed.

and if you know a better way to implement the feature i need instead of my janky code please do let me know.

hello, i can’t post data ke web server because the cors is blocking, what should i do? [duplicate]

new:1 Access to fetch at ‘http://localhost:5000/notes’ from origin ‘http://notesapp-v1.dicodingacademy.com’ has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local

my code :

const Hapi = require("@hapi/hapi");
const routes = require("./routes");

const init = async () => {
  const server = Hapi.server({
    port: 5000,
    host: "localhost",
    routes: {
      cors: {
        origin: ["*"],
      },
    },
  });

  server.route(routes);

  await server.start();
  console.log(`running server in ${server.info.uri}`);
};

init();

i try using cors origin in hapi framework but not still work,

Section with left and right buttons to switch between 0 1 2 elements

So I have this section

<section class="section2 container rounded-pill d-flex d-md-block align-items-center justify-content-between bottomSide">
    <div onclick="switchLeft()">
      <img class="switch-left d-block d-md-none" src="./assets/svg/Arrow-Right-Small.svg" alt="">
    </div>
    <div class="
        rounded-pill row row-cols-1
        row-cols-md-3
        p-4
        justify-content-center
        switches-container">
      <div class="d-flex gap-3 flex-wrap flex-md-nowrap align-items-center justify-content-center">
        <div class="d-flex justify-content-center p-3">
          <img src="./assets/svg/Location.svg" alt="">
        </div>
        <div class="d-flex flex-column gap-1 justify-content-center align-items-center">
          <span class="d-none d-md-block fs-5">Pay Us a Visit</span>
          <span class="small fw-normal">Union St, Seattle, WA 98101, United States</span>
        </div>
      </div>
      <div
        class="d-none d-md-flex border-start border-end border-secondary gap-3 align-items-center justify-content-center">
        <div class="d-flex justify-content-center p-3">
          <img src="./assets/svg/Phone.svg" alt="">
        </div>
        <div class="d-flex flex-column gap-1 justify-content-center align-items-center">
          <span class=" d-none d-md-block fs-5">Give Us a Call</span>
          <span class="small fw-normal">(110) 1111-1010</span>
        </div>
      </div>
      <div class="d-none d-md-flex  gap-3 align-items-center justify-content-center">
        <div class="d-flex justify-content-center p-3">
          <img src="./assets/svg/Email.svg" alt="">
        </div>
        <div class="d-flex flex-column gap-1 justify-content-center align-items-center">
          <span class=" d-none d-md-block fs-5">Send Us a Message</span>
          <span class="small fw-normal">[email protected]</span>
        </div>
      </div>
    </div>
    <div onclick="switchRight()">
      <img class="switch-right d-block d-md-none" src="./assets/svg/Arrow-Left-Small.svg" alt="">
    </div>
  </section>

And the JS code for it is

let indexer = 0
const switchesContainer = document.querySelector(".switches-container")
let children = [];

for (let i = 0; i < switchesContainer.children.length; i++) {
    children[i] = switchesContainer.children[i].innerHTML;
}

// I need to adjust the following JS Code
function switchLeft() {
    switchesContainer.children[0].innerHTML = children[--indexer];


    if (indexer < 0) {
        // Reset Indexer
        indexer = 2
        // Show last one so we start from the end to be switched from start in the left direction
        switchesContainer.children[0].innerHTML = children[indexer]

    }

}

function switchRight() {
    switchesContainer.children[0].innerHTML = children[++indexer];


    if (indexer > 2) {
        // Reset Indexer
        indexer = 0
        // Show last one so we start from the end to be switched from end in the right direction
        switchesContainer.children[0].innerHTML = children[indexer]

    }
}


So there is 3 elements together and left, right arrow, when the screen gets smaller only the first element would be shown and beside it the arrows on each side enter image description here

So know the solution I did, I don’t think it’s good enough so if you have a better solution like when i press that button the element gets transform:translateX(number) or giving it an effect this would be great.

Thank you.

I tried the JS I provided previously and it does what I need but it’s ugly af.

functional implementation of updating a useState variable not changing the value appropriately

I have a function that updates the State values of chatId, currUser, and msg. This function is called twice, so I expect the values to be updated twice. However, the values are only updated once. What am I doing wrong?

This the function:

const displayMessage = (message) => {
    const newMsg = { id: chatId, text: message, sender: currUser };
    setChatId((prevId) => prevId + 1);
    setCurrUser((prevUser) => {
      return prevUser === "user" ? "bot" : "user";
    });
    console.log(`currUser: ${currUser}`);
    setMsg((prevMsg) => [...prevMsg, newMsg]);
  };

This function is being called in fetchApi() and handleSend().

This is the entire code:

import {
  Box,
  TextField,
  Button,
  Typography,
  Avatar,
  Grid,
  Paper,
} from "@mui/material";
import SendIcon from "@mui/icons-material/Send";
import { useState, useEffect } from "react";
import axios from "axios";

const messages = [
  { id: 1, text: "Hi there!", sender: "bot" },
  { id: 2, text: "Hello!", sender: "user" },
  { id: 3, text: "How can I assit you today?", sender: "bot" },
];

function App() {
  const [input, setInput] = useState("");
  const [msg, setMsg] = useState(messages);
  const [chatId, setChatId] = useState(4);
  const [currUser, setCurrUser] = useState("user");

  const fetchApi = async () => {
    try {
      const response = await axios.get(
        `https://www.omdbapi.com/?apikey=213f50cd&t=${input}`
      );
      displayMessage(response.data.Plot);
    } catch (error) {
      console.error(error);
    }
  };

  const handleSend = () => {
    if (input.trim() !== "") {
      console.log(`user input: ${input}`);
      // setCurrUser(currUser === "user" ? "bot" : "user");
      // setCurrUser((prevUser) => (prevUser === "user" ? "bot" : "user"));
      displayMessage(input);
      fetchApi();
    }
  };

  const displayMessage = (message) => {
    const newMsg = { id: chatId, text: message, sender: currUser };
    setChatId((prevId) => prevId + 1);
    setCurrUser((prevUser) => {
      return prevUser === "user" ? "bot" : "user";
    });
    console.log(`currUser: ${currUser}`);
    setMsg((prevMsg) => [...prevMsg, newMsg]);
  };

  const handleInputChange = (event) => {
    setInput(event.target.value);
  };

  return (
    <Box
      sx={{
        height: "93vh",
        display: "flex",
        boxSizing: "border-box",
        flexDirection: "column",
        bgcolor: "grey.200",
        margin: "25px 100px",
      }}
    >
      <Box sx={{ flexGrow: 1, overflow: "auto", p: 2 }}>
        {msg.map((message, index) => (
          <Message key={index} message={message} />
        ))}
      </Box>
      <Box sx={{ p: 2, backgroundColor: "background.default" }}>
        <Grid container spacing={2}>
          <Grid item xs={10}>
            <TextField
              size="small"
              fullWidth
              placeholder="Type a message"
              variant="outlined"
              value={input}
              onChange={handleInputChange}
            />
          </Grid>
          <Grid item xs={2}>
            <Button
              fullWidth
              color="primary"
              variant="contained"
              endIcon={<SendIcon />}
              onClick={handleSend}
            >
              Send
            </Button>
          </Grid>
        </Grid>
      </Box>
    </Box>
  );
}

const Message = ({ message }) => {
  const isBot = message.sender === "bot";

  return (
    <Box
      sx={{
        display: "flex",
        justifyContent: isBot ? "flex-start" : "flex-end",
        mb: 2,
      }}
    >
      <Box
        sx={{
          display: "flex",
          flexDirection: isBot ? "row" : "row-reverse",
          alignItems: "center",
        }}
      >
        <Avatar sx={{ bgcolor: isBot ? "primary.main" : "secondary.main" }}>
          {isBot ? "B" : "U"}
        </Avatar>
        <Paper
          variant="outlined"
          sx={{
            p: 2,
            ml: isBot ? 1 : 0,
            mr: isBot ? 0 : 1,
            backgroundColor: isBot ? "primary.light" : "secondary.light",
            borderRadius: isBot ? "20px 20px 20px 5px" : "20px 20px 5px 20px",
          }}
        >
          <Typography variant="body1">{message.text}</Typography>
        </Paper>
      </Box>
    </Box>
  );
};

export default App;

I tried updating the state variables using the functional way but it still didn’t work.