Why is app.get(‘/’) not being called? – issue with cookies and user login

app.get(‘/’) not being called

Im trying to get cookies to work to let multiple users be logged in at the same time. Right now, users can log in but once they are logged in and refresh the page, they all get logged in as the same user (the one who logged in last). I think this is due to app.get(‘/’) not being called.

This is my code. I’m sorry if it’s a lot, I don’t know which parts could affect the app.get function

let mysql = require("mysql2");

// Vi inkluderar express i vårt projekt
const express = require("express");
const sessions = require("express-session");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const { SourceMap } = require("module");
const { errorMonitor } = require("events");
const { receiveMessageOnPort } = require("worker_threads");
const bcrypt = require("bcrypt");
const { match } = require("assert");
const path = require("path")

// Vi skapar en instans av vår applikation
// genom att anropa express-funktionen
const app = express();

// Vi lägger till HTTP och anropar
// dess serverfunktion och skickar med
// vår express-app
const http = require("http").Server(app);
// Vi lägger till IO, skickar med socket.io
// samt refererar http
const io = require("socket.io")(http);

app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.use(cookieParser());

const oneDay = 1000 * 60 * 60 * 24;

app.use(sessions({
    secret: "secret key",
    saveUninitialized: true,
    cookie: { maxage: oneDay },
    resave: false,
}))

// Vi koncentrerar datan så vi kan läsa den. Är du nyfiken
// på vad extended gör så besök body-parser på npmjs.com
// och skrolla ner till rubriken extended.
app.use(bodyParser.urlencoded({extended: false}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

let connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "MyPassword",
    database: "slutprojekt",
});

var session;

const dirname = './webbsidan'

console.log(__dirname)

// Vi talar om var du ska hamna när någon
// surfar in till vår webbserver. I detta fall
// kommer personen hamna i en mapp som heter
// webbsidan. Där jag kommer placera html-dokument,
// css, bilder etc.
app.use(express.static(path.join(__dirname, '/webbsidan')))

app.get('/', (req, res) => {
    console.log('get /')
    // console.log(req)
    session = req.session;
    
    var Referer = "";
    
    if (req.rawHeaders.indexOf('Referer') != -1){
        
        Referer = req.rawHeaders[req.rawHeaders.indexOf('Referer')+1].split('/')
        Referer = Referer[Referer.length-1]
    }

    console.log(Referer)

    if (Referer != 'login.html' && !session.user){
        res.sendFile('/webbsidan/login.html', {root: __dirname})
    } else if (Referer == 'login.html' && session.user){
        res.sendFile('/webbsidan/index.html', {root: __dirname})
    }
})

app.post('/login', (req, res) => {
    console.log('login-post received');    

    let sql ="SELECT * FROM användare"

    connection.query(sql, function (err, result, fields) {
        if (err) throw err;
        let loggedIn = false

        for (const object of result){
            if (object.AnvändarNamn == req.body.username){
                
                if (bcrypt.compareSync(req.body.password, object.Lösenord)){
                    
                    loggedIn = true;
                    
                    session=req.session;
                    session.user=req.body.username;
                    session.userid=object.AnvändarID;
                    session.sid=req.rawHeaders[req.rawHeaders.indexOf('Cookie')+1]
                    // console.log(req.session)
                    
                    res.redirect('/');
                }
                else {
                    // console.log("fel lösenord")
                }
                break;
            }
            else {
                // console.log('användarnamnet är inte', object.AnvändarNamn);
            }
        }
        if (loggedIn == false){
            res.send('<script>alert("Login failed, try again"); window.location.replace("login.html")</script>')
        }
    })
})

app.post('/updateSchedule', (req, res) => {
    console.log('updating schedule')

    session = req.session;

    let sql1 = `SELECT * FROM kalender_tillgänglig WHERE AnvändarID = ${session.userid}`
    connection.query(sql1, function (err, result, fields) {
        if (err) throw err;
        for (const [key, value] of Object.entries(req.body)) {
            if (value == 'x'){
                // console.log(`${key}: ${value}`)
    
                var dateID = key.split("_")[1]
                // console.log(dateID)
                
                let sql2 = `DELETE FROM kalender_tillgänglig WHERE AnvändarID = ${session.userid} AND dateID = ${dateID}`
                connection.query(sql2, function (err, result, fields){
                    if (err) throw err;
                })
            }
            else if (value != ''){
    
                var dateID = key.split("_")[1]

                let valueString = value.toString();
            
                try {
                    if (err) throw err;
                    
                    const found = result.some(el => el.dateID == dateID) // Check if date already exists in database
                
                    let sql2 = ""

                    if (found) {
                        sql2 = `UPDATE kalender_tillgänglig SET Tillgänglig = '${valueString}' WHERE AnvändarID = ${session.userid} AND dateID = ${dateID}`;
                    } else {
                        sql2 = `INSERT INTO kalender_tillgänglig (AnvändarID, dateID, Tillgänglig) VALUES (${session.userid}, ${dateID}, '${valueString}')`
                    }

                    connection.query(sql2, function(err, result, fields) {
                        if (err) throw err;
                        // console.log(sql2)
                    })
                }
                catch(e){
                    throw e;
                }
            }
        }
    })
    res.redirect('back');
});

app.get('/login', (req, res) => {
    res.redirect('/login.html');
})

app.get('/logout', (req, res) => {

    req.session.destroy();
    // console.log(req.session);
    session = req.session;
    
    res.redirect('/login');
});

// Vi lyssnar efter att någon ansluter till 
// vår socket. När någon gör det så loggar vi
// ut att en användare har anslutit.
io.on("connection", (socket) => {

    if (session){console.log(`${session.user} anslöt.`)} else {console.log('En användare anslöt.')}

    function checkDir(){
        var splitRef = socket.handshake.headers.referer.split('/');
            
        var newSplitRef = [];
    
        for (let i = 3; i < splitRef.length; i++){
            newSplitRef.push(splitRef[i])
        }
        splitRef = newSplitRef
        
        var splitRefString = ""
        splitRef.forEach(element => splitRefString += `/${element}`)

        return splitRefString
    }

    var currentDir = checkDir(); // Här kollas vilken sida användaren är på

    if (currentDir == "/login.html") { // om användaren är på login sidan men redan är inloggad omdirigeras den till startsidan
        if (session != undefined){
            io.emit("redirect", '/')
        }
    }
    else if (session == undefined){ // om användaren inte är inloggad omdirigeras den till login-sidan
        io.emit("redirect", '/login')
    }
    else if ((currentDir == "/") || (currentDir == "/index.html")){ // om användaren är inloggad på startsidan visas en lista med alla användare
        console.log(session)

        connection.connect(function (err) {
            if (err) throw err;
    
            let sql = "SELECT * FROM användare"
            connection.query(sql, function (err, result, fields) {
                if (err) throw err;

                io.emit("result", result);
            })
        });
    }
    else if (currentDir == "/mySchedule.html"){ // om användaren är inloggad på mySchedule sidan ritas kalendern 
        connection.connect(function (err) { // upp med de tiderna användaren redan fyllt i att den är tillgänglig
            if (err) throw err;

            let sql1 = `SELECT * FROM kalender`
            connection.query(sql1, function (err, result, fields) {
                if (err) throw err;
                io.emit("result", result);
            })

            let sql2 = `SELECT * FROM kalender_tillgänglig WHERE AnvändarID = ${session.userid}`
            connection.query(sql2, function (err, result, fields) {
                if (err) throw err;
                // console.log(result)
                io.emit("availability", result);
            })
        });
    }
    else if (currentDir == "/avlblPT.html"){
        connection.connect(function (err) {
            if (err) throw err;
            let sql0 = `SELECT * FROM kalender`
            connection.query(sql0, function (err, result0, fields) {
                if (err) throw err;
                io.emit("result", result0);
            })

            let sql1 = `SELECT AnvändarID FROM användare`
            connection.query(sql1, function (err, result1, fields){
                if (err) throw err;

                var userCount = result1.length
            
                var dateIDList = []

                let sql2 = `SELECT dateID, COUNT(dateID) FROM kalender_tillgänglig WHERE Tillgänglig <> 'x' GROUP BY dateID HAVING COUNT(dateID) > ${userCount-1}`
                connection.query(sql2, function (err, result2, fields) {
                    if (err) throw err;
                    // console.log("res:",result2)
                    result2.forEach(element => {
                        dateIDList.push(element.dateID)
                    })
                    // console.log(dateIDList)
                    dateIDList.forEach(elem => {
                        let sql3 = `SELECT * FROM kalender_tillgänglig WHERE dateID = ${elem}`
                        connection.query(sql3, function(err, result3, fields) { //finner varje datum (ett i taget) där alla är tillgängliga
                            if (err) throw err;
                            
                            var usersHours = []

                            result3.forEach(user => { // loopar igenom användare, här börjar uträkningen för att lista ut vilka timmar alla är tillgängliga 
                                const availablePasses = user.Tillgänglig.split(', ')
                                var availableHours = []
                                
                                availablePasses.forEach(pass => {
                                    const startStop = pass.split("-")
                                    const start = Number(startStop[0])
                                    const stop = Number(startStop[1])
                                    
                                    for (let i = start; i < stop; i++){
                                        availableHours.push(i)
                                    }
                                })

                                usersHours.push({'AnvändarID': user.AnvändarID, 'Tillgänglig': availableHours})
                            })

                            var intersection = usersHours[0].Tillgänglig // detta kodstycke kollar vilka timmar som finns i alla användares tillgänglighetslistor
                            for (let i = 1; i < usersHours.length; i++){
                                intersection = intersection.filter(element => usersHours[i].Tillgänglig.includes(element));
                            }
                            
                            var passes = []

                            function pushTime(pass, tIndex) {
                                passes[pass].push(intersection[tIndex])
                            }

                            function addPass(passIndex) {
                                passes.push([])
                                
                                passIndex += 1
                                return passIndex
                            }

                            var pass = 0
                            addPass(0)

                            for (let j = 0; j < intersection.length; j++){ // detta ska dela upp intersection i pass om det behövs
                                if (j+1 < intersection.length){
                                    if (intersection[j]+1 == intersection[j+1]){
                                        pushTime(pass, j)
                                    }
                                    else {
                                        pushTime(pass, j)
                                        pass = addPass(pass)
                                    }
                                }
                                else {
                                    pushTime(pass, j)
                                }
                            }
                            console.log("done calculating",passes)

                            let sql4 = `SELECT * FROM alla_tillgängliga`

                            connection.query(sql4, function(err, result4, fields) {
                                if (err) throw err;

                                // console.log(result4)

                                // Detta block kallas två gånger. Inte stort problem, bara onödigt
                                // Detta block kollar om det finns några dagar i alla_tillgängliga tabellen där inte alla är tillgängliga
                                result4.forEach(elem => {
                                    // console.log(elem.dateID)
                                    if (dateIDList.includes(elem.dateID) == false){
                                        // console.log(`dateID ${elem.dateID} should be removed from table`)

                                        let sql7 = `DELETE FROM alla_tillgängliga WHERE dateID = '${elem.dateID}'`

                                        connection.query(sql7, function (err, result7, fields) {
                                            if (err) throw err;
                                        })
                                    }
                                })

                                if (passes[0][0]){
                                    // console.log("everyone is available at the same time")
                                    var passStrings = []
                                    passes.forEach(pass => {
                                        var stringStart = pass[0].toString()
                                        var stringStop = (pass[0]+pass.length).toString()
                                        
                                        passStrings.push(`${stringStart}-${stringStop}`)
                                    })

                                    var availabilityString = passStrings.join(", ")
                                    // console.log(availabilityString)

                                    var dateID = result3[0].dateID

                                    const found = result4.some(el => el.dateID == dateID) // Check if date already exists in database
                                
                                    let sql5 = ""

                                    if (found) {
                                        sql5 = `UPDATE alla_tillgängliga SET tider = '${availabilityString}' WHERE dateID = ${dateID}`
                                    }
                                    else {
                                        sql5 = `INSERT INTO alla_tillgängliga (dateID, tider) VALUES (${dateID}, '${availabilityString}')`
                                    }

                                    connection.query(sql5, function(err, result5, fields) {
                                        if (err) throw err;

                                        let sql6 = `SELECT * FROM alla_tillgängliga`

                                        connection.query(sql6, function(err, result6, fields) {
                                            if (err) throw err;

                                            io.emit("availability", result6);
                                        })
                                    })
                                    
                                } else {
                                    // console.log("there is no time during the day where everyone is available")
                                }
                            })

                            
                        })
                    })
                })
            })
        })
    }

    
})

// Istället för app.listen kör vi nu http.listen
http.listen(3000, () => {
    console.log("Servern körs, besök http://localhost:3000");
});

function genDates(start, end){
    var getDaysArray = function(start, end) {
        for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
            arr.push(new Date(dt));
        }
        return arr;
    };

    var newStart = start.toISOString().replace("00:00:00", "10:10:10") // specify time so that no date is skipped or repeated when 
    var newEnd = end.toISOString().replace("00:00:00", "10:10:10") // time is shifted in march and october
    
    var daylist = getDaysArray(newStart, newEnd);

    var datelist= []

    daylist.forEach(element => {
        datelist.push(element.toISOString().split("T")[0])
    })

    var dowNameList = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

    let sql1 = `SELECT dateID, fullDate FROM kalender`
    connection.query(sql1, function (err, result, fields) {
        if (err) throw err;
        
        for (let i = 0; i < daylist.length; i++){
            
            var dowName = daylist[i].toString().split(" ")[0]
            var dowNum = dowNameList.indexOf(dowName)
            
            dowNum += 1
            
            const found = result.some(el => el.fullDate == datelist[i]) // Check if date already exists in database
            
            if (!found){
                let sql2 = `INSERT INTO kalender (dateID, fullDate, dowName, dowNum) VALUES (${i+1}, '${datelist[i]}', '${dowName}', ${dowNum});`
                connection.query(sql2, function (err, result, fields) {
                    if (err) throw err;
                })
            }
        }
    })

    
}

genDates(new Date("2023-01-01"),new Date("2023-12-31"));

WordPress typing test effect only one tyme in one session

I have wordpress website, I have added typing test line in my navigation-top.php file, and it works fine.
I want it to work just one time per session, so when someone clicks on menu categories, or on product the effect don’t work anymore

I just have no idea how I can do it

here are the code I used

window.onscroll = function() {myFunction()};

function myFunction() {
  if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) {
    document.getElementById("typing-demo-div").setAttribute("style", "display:none;");
  } else {
    document.getElementById("typing-demo-div").setAttribute("style", "display:block;");
  }
}
#typing-demo-div{
    position:absolute;
    padding-top:10px;
}
#typing-demo{
    color:black;
width: 90%; 
    width: 100%;
    white-space: nowrap;
    -webkit-animation: typing 10s steps(200, end),
blink-caret .15s step-end infinite alternate;
    overflow:hidden;
    position:static;
}

@-webkit-keyframes typing { from { width: 0; } }

.bisbankstyle{
    font-weight:bold;
    text-decoration:underline;
    color:#F45D48;
}
<div id="typing-demo-div">
    <div id="typing-demo">
     Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
    </div>
</div>

Getting the Text Value in Javascript

In my current process, In the view, when the user clicks on the checkbox, it took the @Item.Extra_Item_Price and Add to the Total Price.

<div class="product__price m-t-5">
  <input class="product__price product__price--large" name="TotalPrice" value="" id="TotalPriceS" type="hidden" />
  <span class="product__price product__price--large" data-original='@Model.ProductPrice'>[email protected](model => model.ProductPrice)</span>
</div>
<div class="product-var p-tb-30">
  <div class="product-quantity product-var__item d-flex align-items-center">
    <span class="product-var__text">Quantity: </span>
    <form class="quantity-scale m-l-20">
      <div class="value-button" id="decrease" onclick="decreaseValue()">-</div>
      <input type="number" id="number" name="number" value="1" />
      <div class="value-button" id="increase" onclick="thisChecked(this)">+</div>
    </form>
  </div>
  <div>
    <h4 class="font--regular m-b-20">Add Some Extra</h4> 
    @if (Model.CustomizableFoods.Count != 0)
    { 
    foreach (var item in Model.CustomizableFoods)
    { 
    <div class="row">
      <ul class="list">
        <li class="list__item">
          <label class="label--checkbox">
            <input type="checkbox" class="checkbox" onclick="thisChecked(this)" value="@item.Extra_Item_Price"> &nbsp; &nbsp; &nbsp; @item.ExtraItem - @item.Extra_Item_Price </label>
        </li>
      </ul>
    </div> 
       }   
      }
  </div>

When the User again unchecks the checkbox it subtracts the amount added.

Here I want to do on submit, want to take the @Item.ExtraItem values that are checked in the view and assign to the Input field to sent to the controller.

Any way of doing this?

This is the Amount updating the current javascript

<script>
        function thisChecked(el) {
            var closest_price_element = $(el).closest('.product-details-box').find('span.product__price');
            var amount = parseFloat(closest_price_element.data('original')) ?? 0; //getting attr value ..

            $('.product-var input[type=checkbox]:checked').each(function () {
                amount += parseFloat($(this).val()); //loop and addiing items amt
            });
            
            closest_price_element.text('Rs.' + amount); //change value of price
            document.getElementById("TotalPriceS").value = amount;
        }

</script>


How to clone elements in an array that will belong to the cloned element that were previously children of the outgoing element?

There is an element that is created via document.createElement, as well as an array of its children. Can you please tell me how to clone both an element and an array of its children, so that these children belong to the cloned element?

For example element and array:

HTML:

<div id="abc"><p id="p1">1</p><p id="p2">2</p></div>

JavaScript:

let el = document.getElementById("abc");

let arr = [];

if(el)
for(let child of el.getElementsByTagName("*")){
  if(child.textContent === "1") arr.push(child);
}

let elClone = el?.cloneNode(true);

//arr.cloneArrFrom(elClone) = [span#p1]???

How can I clone elements in an array so that they are children of node of the cloned element and not loop through all of them again over the cloned element?

I don’t want to constantly loop over the cloned element el.getElementsByTagName(“*”), is there any way to not do this in this case?

I will be grateful for the answer!

How to sequentially create an Element from a string (js)

Help me please! There is a source line html from which it is necessary to create Element sequentially. That is, there is a way to create everything at once, simply by parsing the string through innerHTML or DOMParser, but then to iterate over all the elements, you need getElementsByTagName(“*”), which is very slow. Is there a way to build html sequentially so that it takes each element in a loop?

Let’s say we have an html string:

<div>abc<span class="abc">123</span>567</div>

And, from it to make some code like this:

let parentDiv = document.createElement("div");
for(let i=0;i<3;i++){
  switch(i){
    case 0:
     let txt1 = document.createTextNode("abc")
     parentDiv.appendChild(txt1);
    break
    case 1:
      let el1 = document.createElement("div");
      el1.setAttribute("class","abc");
      for(let j=0;j<1;j++){
        switch(j){
          case 0:
            let txt1 = document.createTextNode("123")
            el1.appendChild(txt1);
          break;
        }
      }
      parentDiv.appendChild(el1);
     break
     case 2:
      let txt2 = document.createTextNode("567")
      parentDiv.appendChild(txt2);
     break
  }
}

Only to generate such code for any valid html string.

I will be very grateful for the answer!

I think that a template will be needed here to create such code, as well as a regular expression regexp for tags. It’s just hard to figure out how to do it.

I need to switch images onlcick using JS

Firstly sorry if this seem a dumb question but I am learning javascript so may have messed this up.

I have an image that clickis replaced by nother image in its place.The problem I am trying to worj out is where do i place the second image link.

HTML below

 <div class="col-lg-3">

<img id="pbook" onclick="imageChange" class="imagebooks"  src="images/pink1.jpg" alt="">


 </div>

Javascript incomplete below:

function imageChange (newImage) {

 var secondImage= document.getElementById("pbook");
  secondImage.style.src = newImage;

}

Thank you for your kind help.

I have tried to create a function that when the image is click by the user is switches to another image. Basically the front image of a book that is then clicked on shows thw bck of the book.

variables in javascript declaration and initialization

It is mentioned in the sources that let and constant variables are not initialized but declared but the code in the snapshot shows the use of the variables without initialization where only constant variable has an impact of not declaring
Can anyone please explain why is this the contradictory part?

How to use react-native-share to share a photo on twitter?

How to use react-native-share to share a photo on twitter? currently when I try to share its sharing the image link instead of proper image how can I share image instead of its uri the image is in the cloud can anyone help me how to do this with my react native app?

 const HandleShareToTwitter = async () => {
        const options = {
            social: Share.Social.TWITTER,
            message: 'Deserunt ea sint magna dolor incididunt sit culpa id laborum cupidata.',
            url: image,
            email: '[email protected]',
            subject: 'Eiusmod esse veniam esse.',
            recipient: '919988998899',
        };
        try {
            const res = await Share.shareSingle(options)
            console.log(res);
        } catch (err) {
            console.log(err);
        }
    }  

Not able to clear Javascript Memoized function cache

I am trying to clear the memoized cache object but tried different solutions like prototype, call and bind but not able to make it work. Any help would be appreciated.

function memoize(func) {
  let cache = {};
  return function() {
    function clear() { cache = {}; }
    const key = JSON.stringify(arguments);
    if(cache[key]) { return cache[key]; }
    const result = func.apply(this, arguments);
    cache[key] = result;
    return result;
  }
}

function square(num) {
  console.log('calling square of', num);
  return num*num;
}

const memoizedSquare = memoize(square);

memoizedSquare(1);
memoizedSquare(1);
memoizedSquare(2);
memoizedSquare.clear(); // getting error on this line
memoizedSquare(2);
memoizedSquare(3);

function addition(a,b,c,d) {
  console.log('calling addition of', a,b,c,d);
  return a+b+c+d;
}

const memoizedAddition = memoize(addition);

memoizedAddition(1,2,3,4);
memoizedAddition(1,2,3,4);
memoizedAddition(4,2,3,1);
memoizedAddition(6,7,8,9);
memoizedAddition(6,7,8,9);

I wrote this code using JsPDF but doesn’t seems to work at all. What is should I use to make this work?

<!DOCTYPE html>
<html>
<head>
  <title>Generate PDF from Text</title>
</head>
<body>
  <h1>Generate PDF from Text</h1>
  
  <textarea id="textInput" rows="10" cols="50"></textarea>
  <br>
  <button id="downloadBtn">Download as PDF</button>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
  <script>
    document.getElementById("downloadBtn").addEventListener("click", function() {
      var text = document.getElementById("textInput").value;
      
      // Create a new jsPDF instance
      var doc = new jsPDF();
      
      // Set the font size and add the text to the PDF
      doc.setFontSize(12);
      doc.text(text, 10, 10);
      
      // Download the PDF file
      doc.save("my_pdf.pdf");
    });
  </script>
</body>
</html>

I am trying to acheive it so that the when I click the button, it allows me download a PDF file containing the things I wrote in the textarea.

How to remove freeze webpage after closing the swal?

Here I am closing the form after form gets submitted successfully with all required fields .
But inside that submit function there is Swal (alert) for confirmation . But after clicking on swal OK button my webpage gets freeze and didn’t respond

const handleCloseModal = () => {
document.getElementById(“modalid”).classList.remove(“show”,”d-block”);
document.querySelectorAll(“.modal-backdrop”).forEach(el => el.classList.remove(“modal-backdrop”));
}
added this function inside the onSubmit function

How can I make inner div to 100% width by rotating vertically if outer div is 10% width?

I have two divs (outer & inner). The outer div’s width is 10%. When I put an inner div with 100% width, it contains inside the 10% width of the outer div. That’s exactly how it should behave.

The problem is that I want to rotate the inner div 90 deg and then it should contain the outer div’s height 100%.

Here is the screenshot of the problem.

Here is what I want to achieve

The solution can be in CSS or in Elementor.

Thank you in advance.

When I rotate the inner div 90 deg, it remains the 10% width of the outer div. But it should expand to 100% of the outer div’s height.

Event Listeners not being removed [duplicate]

This is my function which gets called when a delete button is clicked. The problem here is, inside the if and else part I am adding an event listener and also removing an event listener but the events only get added and not removed and when I click on the button again, it calls those function more than once and that count keeps increasing as the events dont get removed.

export const deleteButtonHandler = () => {
  const deleteButton = document.getElementById('deleteButton');
    const editButtons = document.querySelectorAll('.editIcon');
    const isDeleteMode = deleteButton.dataset.deleteMode === 'true';

    if (isDeleteMode) {
      editButtons.forEach((editButton) => {
        editButton.innerHTML = '<img src="some link to a picture" width="15" height="15">';
        const tagContainer = editButton.parentNode.parentNode;
        const tagText = tagContainer.querySelector('.tagText');

        editButton.removeEventListener('click', () => removeTag(tagText.textContent, tagContainer));
        editButton.addEventListener('click', () => handleTagEdit(tagText));
      });

      deleteButton.textContent = 'Delete Tag';
      deleteButton.dataset.deleteMode = 'false'

    } else {
      editButtons.forEach((editButton) => {
        const editIcon = document.createElement('img');
        editIcon.src = "some link to a picture";
        editIcon.width = "15";
        editIcon.height = "15";
        
        editButton.innerHTML = '';
        editButton.appendChild(editIcon);
        
        const tagContainer = editButton.parentNode.parentNode;
        const tagText = tagContainer.querySelector('.tagText');
      
        editButton.removeEventListener('click', () => handleTagEdit(tagText));
        editButton.addEventListener('click', () => removeTag(tagText.textContent, tagContainer));
      });

      deleteButton.textContent = 'Cancel';
      deleteButton.dataset.deleteMode = 'true';
    }
  };

and the if-else part works perfectly I checked it, with each click it alternates with if and else block of code.

Why is only the last object re-rendering in ReactJS when setting an array in useState?

I need to access promise Value that was returned from AWS amplify datastore. I tried using Async/await to access the promise, it didn’t work.

How should I access this promise result (React, DataStore, AWS Amplify)

this was the same problem I was facing and I tried the solution recommended by @Azzy. but it didn’t work.

if(orderResponse?.id) { const dishResponse = await DataStore.query(OrderDish, (c) => c.orderID?.eq(orderResponse.id)); console.log('dish', dishResponse); setDishes(dishResponse); }

when I tried this I got the same results. (Dish details were returned as a promise)

since it didn’t work, Then I used the useState

const [dishes, setDishes] = useState();

dishes to map the data to get the objects out of the array so I can access the orderDishDishid values to retrieve Dish data. below is the code used to map and set data in react usestate

const [orderDish, setOrderDish] = useState([]);

useEffect (() => { dishes?.map((orderdishItem) => ( setOrderDish(orderdishItem) ) ) },)

here when I console.log(orderdishItem) all the objects are showing in the console.

but only the last object is set to the “orderDish” in the usestate
const [orderDish, setOrderDish] = useState([]);

when console.log(orderDish)
only the last object is re rendering

I want to set all four objects in the useState to access the Dish Details.

please let help me to understand why only the last object is re-rendering. what i have done wrong and how to set all objects in to

const [orderDish, setOrderDish] = useState([]); using dishes?.map

if you can provide code snippets that would be really helpful.