How do I get messages to appear right away? It works for new conversations (first block), but not for the existing conversations (second block)

The below code works for addNewConvo (new conversations), but not for addMessagetoConversation (existing conversations). I thought I did the same process for both, but I am missing something in the second part. Thank you in advance!

  const addNewConvo = useCallback(
    (recipientId, message) => {
      const newConversations = conversations.map((convo) => {
        if (convo.otherUser.id === recipientId) {
          //  convo.messages.push(message);
          //  convo.latestMessageText = message.text;
          //  convo.id = message.conversationId;
          return {
            ...convo,
            messages: [...convo.messages, message],
            latestMessageText: message.text,
            id: message.conversationId
          }
        }
        return convo
      });
      setConversations(newConversations);
    },
    [setConversations, conversations]
  );

  const addMessageToConversation = useCallback(
    (data) => {
      // if sender isn't null, that means the message needs to be put in a brand new convo
      const { message, sender = null } = data;
      if (sender !== null) {
        const newConvo = {
          id: message.conversationId,
          otherUser: sender,
          messages: [message],
        };
        newConvo.latestMessageText = message.text;
        setConversations((prev) => [newConvo, ...prev]);
      }

      conversations.forEach((convo) => {
        if (convo.id === message.conversationId) {
          //  convo.messages.push(message);
          //  convo.latestMessageText = message.text;
          return {
            ...convo,
            messages: [...convo.messages, message],
            latestMessageText: message.text,
          }
        }
        return convo
      });
      setConversations(conversations);
    },    
    [setConversations, conversations]
  );

forEach array getting error TypeError: Cannot read property ‘forEach’ of undefined

im trying to clean some sheets, individually i make it work uncommenting and changing sheet name

function doClean(sheet) 
{
// var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Resultado");

var LR = sheet.getLastRow();
var LC = sheet.getLastColumn();

sheet.getRange(1,1,LR,LC).getDisplayValues()
sheet.createTextFinder("-").matchEntireCell(true).replaceAllWith("");
sheet.createTextFinder("0").matchEntireCell(true).replaceAllWith("");
sheet.createTextFinder("0,00").matchEntireCell(true).replaceAllWith("");
sheet.createTextFinder("0,0000").matchEntireCell(true).replaceAllWith("");
};

but when when i try to group in array and execute with foreach

function doCleanSheets() {
 var sheet = ["BLC", "Balanço", "DRE", "Resultado", "FLC", "Fluxo", "DVA", "Valor"];
 SpreadsheetApp.getActive().sheet.forEach(doClean);
};

im getting error

TypeError: Cannot read property ‘forEach’ of undefined
doCleanSheets @ – 10x_to_11x.gs:87

line 87 is SpreadsheetApp.getActive().sheet.forEach(doClean);

searched for error, but results were way more complex than my case, and i couldnt apply

How can I change the text inside my dynamically created button’s with jQuery?

I have reviewed How can I change the text inside my <span> with jQuery? to get where I am. However, that does not cover dynamically created buttons.

I am creating buttons dynamically which contain a label.

$("<button type='button' id='" + this.patExeId 
                + "' name='exerciseMachine' class='btn exeBtn btn-large col-lg-2 col-md-2 col-sm-2 col-3 m-1 p-3' "
                + "value='" + this.exeName + "'>" + this.exeName + " <span class='label label-light label-as-badge'>0</span></button>").appendTo($("#allExercises"));

enter image description here

The three “this.patExeId” values are

  • OA==
  • Mg==
  • Mw==

I want to update the label as exercise sets are completed. I am using this test code that is triggered when the button is clicked:

$('#'+$(this).attr('id')+ ' span').html('3');

This is triggering an error shown in the console log:

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: #OA== span

Try Catch methods are throwing promises [duplicate]

let metadata = allNFTs.map(async (e) => {
      try {
        const res = JSON.parse(e.metadata.attributes);
        return res;
      } catch (err) {
        // throw err;
        let config = {
          method: "get",
          url: `http://localhost:3000/api/fetch`,
          header: {
            "Content-Type": "application/json",
          },
        };
        const res = await axios(config);
        console.log(res.data.attributes);
        return res.data.attributes;
      }
    });
console.log(metadata);

I want use try catch method like this but all i can get bunch of promises on my console

enter image description here

When i tried if statement my next.js app throwing me that error. I want to do something if e.metadata.attributes is empty or null or undefined but my app throwing errors.

React app, Images not downloading after npm build

After npm run build in react.js@18 application. some of the <img src=‘images/logo.png’> tag stopped working. I’ve coded exactly same path in 2 react component. but image is not showing in only one component. .

I am using logo.png in <body><nav> & <body><header> creted by react components.

I’m also using logo.svg in <head> tag in index.html

After npm build and deploy by gh-pages, the image in ` does not load.

I can still see image in which is loded with landing page,

comes when someone click on **Home** NavLink (*Seems some code in react-router is not working. but this question is for image issue..*)

The difference I see in the two logo.png requests is, My non woring component is trying to load the image as text/HTML as per Chrome-Network-tab,

Chrome network tab

I found this article in official documentation, but my logo.png is outside of src folder. So I can not use import in react component. Moreover, its working without import in one component, so I’m unable to figure out.

Discord.js: TypeError: Cannot read properties of undefined (reading ‘has’)

I am creating a Discord music bot using discord.js version 13.6.0 and discord-player but I keep getting this error, here is my code:

const { MessageEmbed, Permissions } = require('discord.js');

module.exports = {
    name: 'stop',
    aliases: [],
    utilisation: '{prefix}stop',
    voiceChannel: true,

    execute(client, message) {
        if (message.member.id.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
            // Stop the player
        };
    },
};

The error I get when running that command:

if(message.member.id.permissions.has(Permissions.FLAGS.KICK_MEBERS)){

TypeError: Cannot read properties of undefined (reading ‘has’)

I don’t know why this is happening, please could someone help me?

HOW DO I FIX ERROR IN DEPLOY HEROKU: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80

I can’t find the problem when deploying to Heroku.
I have already reviewed the code but to no avail.

Apparently, it is something related to some request that is not error handling:

I suspect 2 snippets of the code, because when removing the file they are, the deploy happens normally.

The snippets are:

Reading a .p12 certificate

let cert = fs
    .readFileSync(path
      .resolve(__dirname, `../certs/${ process.env.GN_CERT }`));

Or generating a buffer with the credentials:

 const credentials = Buffer.from(
    `${ clientID }:${ clientSecret }`
  ).toString('base64');

Note: clientID and clientSecret are strings.

ERROR:

2022-04-23T22:13:30.578225+00:00 app[web.1]: (node:22) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80
2022-04-23T22:13:30.578225+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
2022-04-23T22:13:30.578225+00:00 app[web.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2022-04-23T22:13:30.578305+00:00 app[web.1]: (node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error either by throwing inside of a sync function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
2022-04-23T22:13:30.578341+00:00 app[web.1]: (node:22) [DEP0018] DeprecationWarning: Unhandled promises rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I would appreciate it if you can help.

How to append two HTMLElements into one Javascript

So, i have two HTMLElements that i get using:

var el1 = document.getElementById('div1')
var el2 = document.getElementById('div2');

what i want to do is merge this 2 elements that are inserted inside two containers like below:

<container-x1>
    <container-x2>
        <div id="div1">test1</div>
    </container-x2>
</container-x1>

<container-y1>
    <container-y2>
        <div id="div2">test2</div>
    </container-y2>
</container-y1>

my goal after this is to remove completely remove the container y1 and merge test 1 and test 2 into same container like this:

<container-x1>
    <container-x2>
        <div id="div2">test1  test2</div>
    </container-x2>
</container-x1>

any help? thanks in advance

why XMLHttpRequest too slow with my codes?

i code some simple form and decided to use XMLHttp Request to submit data to a php file but its seems is slow compared to using php. Is there anything i can do to make this fast. I’m getting mad at it because i have to hit the submit button like 3 times before the page moves to the next page

xmlr.open('POST', 'form/i.php');
    
    
    var fnam = document.getElementById('firstname-input').value;
   
    
    
    xmlr.onload = function () {
      if (this.status === 200) {
       
        
        function movON() {
            
 
            
          window.location.href = "features.php"
          
          
    
        }
         setTimeout(movON, 1000); 
        
        
      } else {
        console.log('error');
      }
    }
    
    xmlr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    xmlr.send('&fxnam=' + encodeURIComponent(fnam) )
            

Click Listener in Java Script

I’m New in JS World and i have a problem
I had a button and i register a listener in this button in JS File and Remove the Listener
Once User Clicked this Button the reigister function is onSaveBtnClicked
Ex:

function onSaveBtnClicked() {
clickedDiv.append(createWeeklyDiv());
console.log("== Hello From Weekly Button ==");
saveEventBtn.removeEventListener('click', onSaveBtnClicked);}

and i do the same on another file

function onSaveBtnClicked() {
clickedDiv.append(createDailyDiv());
console.log("== Hello From Daily Button ==");
saveEventBtn.removeEventListener('click', onSaveBtnClicked);}

The Problem is when i clicked On Button on Daily View then I clicked it from another view
there is two output in the console the first is Hello From Daily Button and the second output is Hello From Weekly Button which mean that The button didn’t remove the first Listener
Output

sending client auth code to express server to allow server to modify client spreadsheets

I wanted to make a simple app that would ask user’s permission to create and modify spreadsheets on their drive. The client would log in, and then send their log-in details to the Express server to handle api calls on behalf of the user. As far as I’m aware, this is possible with GAPI.
I begun following these instructions and implementing them into my code:

  1. Resource 1
  2. Resource 2

I went onto G Cloud Platform and created the project and enabled Sheets Api. I created OAuth 2.0 creds and an api key. I also set the “Authorized JavaScript origins” and “Authorized redirect URIs” to my public site’s IP and tried setting it to allow from localhost:8000 but THAT part doesnt work. So to test changes, I have to publish EVERY commit to heroku. but thats not the real problem.

The real problem is that I have no idea how to allow the server to modify the client’s sheets in their place. I follow this resource to get started with the code, since it looked mostly backend, but then it gets the OAuth2.0 token by generating a link and asking the user to “go to it and insert the code found on the link” (the link is a google sign in page that will redirect).
Upon signing in, nothing happens except the URL gets a code parameter. Problem is, I couldn’t get the server to redirect the user to the site, then back, to get the url params without CORS throwing a fit. This attempt was a simple Express route. When a user calls /sheets, it would first try to authenticate, then create a sheet. I had a auth method prepared that looks like this:

    const {google} = require('googleapis');
const sheets = google.sheets('v4');
const readline=require("readline")
const fs = require("fs")
const TOKEN_PATH = 'token.json';
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.

const auth=(req,res,next)=>{
    // Load client secrets from a local file.
    fs.readFile('./utils/credentials.json', (err, content) => {
        if (err) return console.log('Error loading client secret file:', err);
        // Authorize a client with credentials, then call the Google Sheets API.
        const {client_secret, client_id, redirect_uris} = JSON.parse(content);
        const oAuth2Client = new google.auth.OAuth2(
            client_id, client_secret, redirect_uris[0]
        );
        // Check if we have previously stored a token.
        fs.readFile(TOKEN_PATH, (err, token) => {
          console.log(err,token);
            if (err){
                const authUrl = oAuth2Client.generateAuthUrl({
                  access_type: 'offline',
                  scope: SCOPES,
                });
                console.log("redirecting");
                console.log(authUrl);
                // res.header("Access-Control-Allow-Origin", "*")//attempt to bypass cors. doesnt work
                res.redirect(authUrl)//redirect to URL generated to auth. wont work because of CORS. 
            }else{
              oAuth2Client.setCredentials(JSON.parse(token));
              // callback(oAuth2Client);
              next()
            }
        });
    });
}
module.exports=auth

but this was just my first attempt. I know this site practically bans people for asking questions, so I wanted to give it as many attempts as possible before posting and logging EVERYTHING. The second attempt was to follow how to auth through the client. The next resource I used was this: resource 4. On here, the scripts would create an auth button and a log out button and then display some basic data from a spreadsheet, courtesy of Google. This works, but its not feasible to have the client make the calls to gapi for my project. So, I created a button that would create the spreadsheet if the user is logged in. The code is this:

async function main () {
    const googleAuth = gapi.auth2.getAuthInstance()
    const googleUser=googleAuth.currentUser.get()
    console.log(googleUser);
    const TOKEN =googleUser.getAuthResponse().id_token
    console.log("token: "+TOKEN);
    const response = await fetch(`/sheet`, {
        method: 'POST',
        body: JSON.stringify({
            token:TOKEN
        }),
    });
    if (response.ok) {
        console.log("success");
    } else {
        alert(response.statusText);
    }
}
document.getElementById("create_spreadsheet_btn").addEventListener("click",(event)=>{
    event.preventDefault()
    main();
})

now, the resource that easily explains how to create a spreadsheet is this: resource 5, but in it, it requires the user’s auth/log/whatever. I honestly dont know, and the documentation refers to this: resource 6 to authenticate a user. But that is where thats just resource 3 all over again. I just couldnt get express to redirect the user to the auth screen because of CORS.

Honestly, I love the amount of simple document Google has, but I feel like they left out the MOST important part; the authentication! it sucks when resource 5 has almost everything but the way to get the server to act as the user with their credentials (the bottom part).

How is something like this supposed to work? I’m assuming that signing it through the client side is super easy, and their examples do that just fine, but how is an express server supposed to know you’re signed in? And how is it supposed to make API calls without your credentials? I even tried getting the current user’s id_token and passing that through, but it still says the “user is not logged in” on the server side. How do I pass through a logged in user on the server side?

So far, all I got is this:
Client side:

async function main () {
    const googleAuth = gapi.auth2.getAuthInstance()
    const googleUser=googleAuth.currentUser.get()
    console.log(googleUser);
    const TOKEN =googleUser.getAuthResponse().id_token
    console.log("token: "+TOKEN);
    const response = await fetch(`/sheet`, {
        method: 'POST',
        body: JSON.stringify({
            token:TOKEN
        }),
    });
    if (response.ok) {
        console.log("success");
    } else {
        alert(response.statusText);
    }
}
document.getElementById("create_spreadsheet_btn").addEventListener("click",(event)=>{
    event.preventDefault()
    main();
})

server side, express routing:

const Router=require("express").Router()
//const auth=require("../utils/auth") couldnt redirect user. 
const {google} = require('googleapis');
const sheets = google.sheets('v4');
Router.get("/",(req,res)=>{
    res.render("home")
})
Router.post("/sheet",async (req,res)=>{
    try {
        console.log("req.body: "+req.body);
        console.log("req.body.token: "+req.body.token);
        const request = {
            resource: {
            // TODO: Add desired properties to the request body.
            },
            auth: req.body.token, //WHAT IS THE AUTH? WHAT DOES THIS EVEN LOOK LIKE? 
        };
        // google.client.setToken({
        //     access_token: req.body.token
        //   })
        const response = (await sheets.spreadsheets.create(request)).data;
        // TODO: Change code below to process the `response` object:
        console.log(JSON.stringify(response, null, 2));
        res.json("User is logged in")
    } catch (error) {
        console.error(error);
        res.json(error)
    }
})
module.exports=Router

I appreciate any advice! Please dont downvote, I really did my research. (there like 20 stackoverflow resources, but none of them are bring new insight)

HTML element “top” style being set generated random number but not moving to the position in JavaScript

I have been working on a project and remaking snake. The code is all supposed to set the position of the apple to a random number and it logs it as doing so, but the apple stays in the same place. The position type is “relative” so it stays within a box. This is my first time using HTML and Javascript together. The code just doesn’t work (no errors or warnings). The random number generation code is as follows:

function rand(min, max, step) {
    var delta,
        range,
        rand;
    if (arguments.length < 2) {
        max = min;
        min = 0;
    }
    if (!step) {
        step = 1;
    }
    delta = max - min;
    range = delta / step;
    rand = Math.random();
    rand *= range;
    rand = Math.floor(rand);
    rand *= step;
    rand += min;
    return parseInt(rand);
}

The code for setting the “apples” position (in js):

function generateApple() {
    let y = parseInt(rand(-15, 470, 15))
    apple.style.top = y
    console.log(apple.style.top)
}

It does successfully print the new location but doesn’t move the “apple” HTML object to the position. I have the initial position set to 15 in style.left and 15 in style.top. The CSS for the apple is as follows:

.apple {
    height: 15px;
    width: 15px;
    background-color: red;
    border: 2px;
}

The full code is on this website: https://passionproject.on.fleek.co