Fullscreen keybinds inside an electron app not working

In an ordinary electron app, regular application etiquette of the OS the user is using is applied. However, for me (Using Windows OS), the F11 keybind (typically used to put apps into fullscreen and out of fullscreen) only works for putting my electron app in fullscreen. Once in fullscreen, when the button is pressed again, it does not revert back to the application’s original size before going into fullscreen, instead doing nothing and requiring me to implement a button to take the app out of fullscreen.

Here is the app in question:

const { app, BrowserWindow, screen, ipcMain } = require('electron');

let max = true;

const createWindow = () => {
  const targetDisplay = screen.getPrimaryDisplay();
  let {width, height} = targetDisplay.workAreaSize;

  const win = new BrowserWindow({
    width: width,
    height: height,
    icon: "icon.png" ,
    fullscreen: false,
    autoHideMenuBar: true,
    frame: false,
    transparent: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      allowRunningInsecureContent: true
    }
  });

  win.loadFile('src/os/index.html');

  win.on('move', () => {
    const targetDisplay = screen.getDisplayMatching(win.getBounds());
  });

  win.on('enter-full-screen', () =>{
    win.webContents.send('fullScreen');
  })

  win.on('leave-full-screen', () =>{
    win.webContents.send('fullScreen');
  })

  ipcMain.on('closeWindow', () => {
    win.close();
  });
    
  ipcMain.on('minimizeWindow', () => {
    win.minimize();
  });
    
  ipcMain.on('resizeWindow', () => {
    const targetDisplay = screen.getDisplayMatching(win.getBounds());
    const { width, height } = targetDisplay.workAreaSize;
    if (max === false) {
      win.setPosition(targetDisplay.bounds.x, targetDisplay.bounds.y, true);
      win.setSize(width, height, true)
      max = true;
    } else {
      win.setPosition(targetDisplay.bounds.x + width/4.0, targetDisplay.bounds.y + height/4.0, true);
      win.setSize(width/2.0, height/2.0, true);
      max = false;
    }
  });
}

app.whenReady().then(() => {
    createWindow();
});
  
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
  
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  };
});


I at first thought this was due to electron not being able to run browser insecure content. However, after specifying to the window that it was allowed to run insecure content, with the lineallowRunningInsecureContent: true, the same issue continued.

Any ideas why this might be?

Can I get assistance on this app XYZEnterprises

How to code XYZ Enterprises app that have 3 different languages which is English,French, Spanish change language on first interface using java language on Android studio

I have try to code using my experience then keep giving me errors then I was expecting it to run and on the first interface have to show text view saying welcome to XYZ ENTERPRISES and button that says next and give the option to change languages then on the next interface have to say You’re one step cloer

“Http failure response for http://servername/article: 0 Unknown Error” Angular

My code runs fine on localhost but when i upload it on a remote server it gives me two errors:

Access to XMLHttpRequest at ‘http:servername:4000/getArticleContent’ from origin ‘http://servername’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

and

  1. message: “Http failure response for http://64.227.111.22:4000/getArticleContent: 0 Unknown Error”

  2. name: “HttpErrorResponse”

Please i need urgent help

I have added cors on the server file and i tried using proxy then i tried adding the port number to it

PHP receives no parameter via AJAX

I try to hand over a parameter, a String, that is determined by user input via Ajax to a PHP Programm, but the php does not receive the parameter I try to handover. Then Ajax should return a JSON

const category = document.getElementById('genreSelect').value;

            $.ajax({  
            type: 'GET',  
            url: 'button.php', 
            data: { category: category } ,
            success: function(response) {                
            console.log(response);
                

    }
});
<?php

header('Content-Type: application/json');

$kate ="";
if(isset($_POST['category'])) {
        $name = $_POST['category'];
        $kate =$name;
        echo $name;
    } else {
        echo "No name parameter received.";
    }
echo json_encode($kate);
?>

I have tried several other Ajax commands, but they did not work.

Threshold seems to break my website, IntersectionObserver not working as intended

Recently I’ve tried to follow a youtube tutorial on scroll animations using IntersectionObserver, I followed step by step but it seems when min-weight is set to 100vh, 2 sections load in at the same time, not allowing the 2nd one to ever change.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll Tutorial Beyond Fireship</title>

    <link rel="stylesheet" href="style.css">
    <script defer src="app.js"></script>
</head>
<body>

    <section class="hidden">
        <h1>Hi Mom!</h1>
        <p>This is my website</p>
    </section>

    <section class="hidden">
        <h2>Buy my products</h2>
        <p>
            The things you own end up owning you.
            It's only after you lose everything that you're free to do anything
        </p>
    </section>

    <section class="hidden">
        <h2>It's really good</h2>
        <div class="logos">
            <div class="logo hidden">
                <img src="Images/icons8-steam-75.png">
            </div>
            <div class="logo hidden">
                <img src="Images/icons8-nintendo-switch-logo-75.png">
            </div>
            <div class="logo hidden">
                <img src="Images/icons8-ps5-75.png">
            </div>
            <div class="logo hidden">
                <img src="Images/icons8-xbox-75.png">
            </div>
        </div>
    </section>

</body>
</html>`

`let observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
        console.log(entry) //check
        if (entry.isIntersecting){
            entry.target.classList.add('show');
        } else{
            entry.target.classList.remove('show');
        }
    })
});

let hiddenElements = document.querySelectorAll('.hidden');
hiddenElements.forEach((el) => observer.observe(el));`

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;700&display=swap');
body{
    background-color: black;
    color: white;
    font-family: 'Poppins', sans-serif;
    padding: 0;
    margin: 0;
}

section{
    display: grid;
    place-items: center;
    align-content: center;
    min-height: 100vh;
}

.hidden{
    opacity: 0;
    filter: blur(5px);
    transform: translateX(-100%);
    transition: all 1.5s;
}
.show{
    opacity: 1;
    filter: blur(0);
    transform: translateX(0);
}
.logos{
    display: flex;
}
.logo{
    margin: 1rem;
}
.logo:nth-child(2){
    transition-delay: 200ms;
}
.logo:nth-child(3){
    transition-delay: 400ms;
}
.logo:nth-child(4){
    transition-delay: 600ms;
}

@media(prefers-reduced-motion){
    .hidden{
        transition: none;
    }
}

I tried setting min-height to 101vh which works, and adding threshold 0.5, which breaks my website.

FirebaseError: Invalid document reference. Document references must have an even number of segments, but table/table1/recipe0 has 3

I have a college project that uses react native to create a app, we have to use firebase to make the database and use it inside of hte pages, i have a problem where i have a page that you can look at the products, this page has a button that when pressed it changes the product in the page and shows the next one, i have 5 buttons at the top of the page to assign to different tables, i basically have to access a specific field of the subcollection of the collection but it returns the error in the title everytime i press the button:

Firebase:
enter image description here

code:
`

  const [trocar, setTrocar] = useState(0);
    const [selectedTable, setSelectedTable] = useState(1);
    const [ldata, setLData] = useState({});


const incrementRecipeTab = async (trocar, selectedTable) => {
        try {
            // Determine the subcollection path based on the selected table
            const subcollectionName = `table${selectedTable}`;
            
            // Document reference for the specific recipe
            const recipeDocPath = `table/${subcollectionName}/recipe${trocar}`;
            const recipeDocRef = doc(db, recipeDocPath);
            
            // Log the path to debug
            console.log(`Document path: ${recipeDocPath}`);
            
            // Get the document snapshot
            const recipeDocSnapshot = await getDoc(recipeDocRef);
            
            if (recipeDocSnapshot.exists()) {
                // Increment the specific recipe field
                await updateDoc(recipeDocRef, {
                    [`recipe${trocar}`]: increment(1) // Increment dynamically
                });
    
                console.log(`Recipe ${trocar} incremented successfully for table ${selectedTable}`);
            } else {
                console.error(`Recipe document does not exist for table ${selectedTable} at path ${recipeDocPath}`);
            }
        } catch (ex) {
            console.error('Error incrementing recipe:', ex);
        }
    };

    const handleAddPress = () => {
        // Adicionar logs para debug
        console.log('Current Recipe:', trocar);
        console.log('Table ID:', selectedTable);
    
        // Validar os valores antes de chamar a função
        if (trocar != null && selectedTable != null) {
            incrementRecipeTab(trocar, selectedTable);
        } else {
            console.error('trocar or selectedTable is not defined');
        }
    };

    
    const renderItem = (item) => (
        <View>
            {item && (
                <View style={[styles.container, { marginTop: 8 + rowGap }]}>
                    <View style={styles.column}>
                        <Image source={item.image} style={styles.imagPrato} />
                        <View style={styles.textBoxContainer}>
                            <Text style={styles.boxText}>{item.name}</Text>
                            <Text style={styles.boxTextTemp}>{item.time} Minutes</Text>
                            <View style={styles.imageVectorContainer}>
                                <Image source={require("../assets/Vector.png")} style={styles.imageVector} />
                            </View>
                            <View style={styles.rectangle}>
                                <Text style={[styles.boxText, { color: 'white', top: '31%', position: 'relative' }]}>Recipe:</Text>
                            </View>
                            <View style={[styles.rectangle, { left: '55%' }]}>
                                <Text style={[styles.boxText, { color: 'white', top: '31%', position: 'relative' }]}>Price: {item.price} €</Text>
                            </View>
                            <View style={styles.textboxContainerIngre}>
                                <Text>{item.recipe}</Text>
                            </View>
                            <View style={styles.rectangleCenter}>
                                <Text style={[styles.boxText, { color: 'white', top: '31%', position: 'relative' }]}>Preparation:</Text>
                            </View>
                            <View style={[styles.textboxContainerIngre, { top: '160%' }]}>
                                <Text>{item.preparation}</Text>
                            </View>
                            <TouchableOpacity onPress={() => handleAddPress()} style={styles.rectangleadd}>
                                <Text style={[styles.boxText, { color: 'white', top: '31%', position: 'relative' }]}>Add: {item.quant}</Text>
                            </TouchableOpacity>
                        </View>
                        <Button onPress={HandlePress} title="Next" />
                    </View>
                </View>
            )}
        </View>
);    `

If someone want more parts of the code, just ask

I want to increment the recipe[trocar], trocar being the current product in the assigned selecttable that shows in the page, i can’t seem to get why it’s showing that error

Query an existing local SQLite file in frontend HTML/Javascript without a local host

I’m working with a program that dumps large SQLite files as outputs, and I want to build an interface for users to explore them visually. I’d like to do this using an HTML file with Javascript / D3 code. I want the user to be able to double-click the HTML file and open in a browser, so ideally no local hosting or backend.

I’ve tried the “example HTML file” in the SQL.Js Readme, as well as a number of other examples from that repository. I’ve copied in the js / wasm files from sql.js locally as well as tried a CDN, but can’t seem to get it to work. An example / simplified directory is below:

mydatabase.sql <– this will be overwritten periodically and the user would need to refresh the html file in browser to reload changes.
mydashboard.html <– this would have “mydatabase.sql” as a hard-coded variable (the file name / location would not change), would have a basic HTML layout as well as a bunch of D3 code for visualization.

Pseudocode for what I’m imaging in Javascript is as follows:

const MY_FILE_PATH = 'mydatabase.sql'
const db = mySQLConnectionFunction(MY_FILE_PATH) 
const response = db.myExecuteQueryMethod("SELECT * FROM XYZ")
console.log(response)

The minimum working condition I’m trying to achieve is to have an html file that references “mydatabase.sql” and can execute a pre-written query within the browser and without a backend or local host. Will not need write access to the SQL file.

I know file access is intentionally restricted for front-end Javascript, but it seems like it should be doable if the HTML file and SQLite file are in the same directory. Any help would be greatly appreciated!

Square Color Not Changing

I made tiles of square with HTML,CSS, and Javascript and I’m trying make clickable squares and the color of the square must change to the #e3ff17 simultaneously. If I click that same square, the color must go back to normal.

I’ve tried multiple ways, but none of them worked. I cannot even click on it. How do I make the tiles or squares clickable and change the color, and switch the color back to original when I click it again? Here is my code:”

function changeBackgroundColor(event) {
  var color = "#eaef44";
  event.style.changeBackgroundColor = color;
}
* {
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  place-items: center;
  justify-content: center;
  overflow-x: hidden;
  height: 100vh;
}

.container {
  display: grid;
  place-items: center;
  justify-content: center;
}

.div {
  display: flex;
  justify-content: center;
  /*Add this line*/
}

#cont {
  display: grid;
  grid-template-columns: 1fr;
}

.square {
  margin: .5px;
  width: 60px;
  height: 60px;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.9);
  list-style: none;
  display: grid;
  place-items: center;
  font-size: 0;
}
<div class="square" id="D14" style="background-color: #eee1c6;" onclick="changeColor()"></div>
<div class="square" id="E14" style="background-color: #00a881;"></div>
<div class="square" id="F14" style="background-color: #eee1c6;"></div>
<div class="square" id="G14" style="background-color: #00a881;"></div>
<div class="square" id="H14" style="background-color: #eee1c6;"></div>
<div class="square" id="I14" style="background-color: #00a881;"></div>
<div class="square" id="J14" style="background-color: #eee1c6;"></div>
<div class="square" id="K14" style="background-color: #00a881;"></div>

Angular lazy loading component and service

May you explain me some fact? I have this code

sharedservice.ts


@Injectable({
  providedIn: 'root'
})
export class SharedService {
  id = (new Date()).getTime();
}

main.ts

export const ROUTES: Route[] = [
  {
      path: 'lazycomp',
      loadComponent: () =>
          import('./lazycomp.component').then(
              (mod) => mod.LazycompComponent
          ),
  },
];

@Component({
  selector: 'app-root',
  standalone: true,
  template: `

    {{serv.id}}

    @if(!(loaded$ | async)) {
      <button (click)="load()">
          Load advanced settings
      </button>
    }
    <ng-container *ngComponentOutlet="comp" />
  `,
  imports:[CommonModule],
  providers: []
})
export class App {
  loaded$ = new BehaviorSubject<boolean>(false);
  comp: any;

  readonly serv = inject(SharedService);

  async load() {
    this.comp = await import('./lazycomp.component').then((mod) => mod.LazycompComponent);
    console.log(this.comp);
    this.loaded$.next(true);
  }
}

bootstrapApplication(App);

lazycomp.component

@Component({
  selector: 'app-lazycomp',
  standalone: true,
  imports: [LazycompimpComponent],
  template: `
    lazy  =  {{serv.id}}
  `,
  styles: ``,
  providers: []
})
export class LazycompComponent {
  readonly serv = inject(SharedService);
}

lazycompimp.component

@Component({
  selector: 'app-lazycompimp',
  standalone: true,
  imports: [],
  template: ``,
  styles: ``,
  providers: [SharedService]
})
export class LazycompimpComponent {

}

I press button, load lazycomp and get 1717188440363 lazy = 1717188440363.

Ok. service instance is singleton and on root injector.

After that I add providers: [SharedService] to lazycomp and get 1717189116834 lazy = 1717189194305

How it work? Why imports: [LazycompimpComponent] in lazycomp does not put SharedService to providers?

I thought that lazy loaded module (standalone component module too?) create own root injector.

Exception in Node.js [closed]

Our center of attention is ServiceToService.setClientLoggingInResponse() method (which is called from RequestProcessor class line:12) . I have log printing the following output from bottom to top. We see memcache error on third logged statement. It occurs in MCache.readFromCache() method then it goes to catch block of RequestProcessor class (line 15 of RequestProcessor class). I am unable to comprehend why it is in catch block of RequestProcessor. Because I thought I have everything cover in setClientLoggingInResponse(). I thought if memcache error arises it should go to line 48 in setClientLoggingInResponse() method. But as log shows it didn’t. I have two questions.

  1. Why it didn’t end up in line 48 in setClientLoggingInResponse() method but rather end up in catch block (line 15 of RequestProcessor class)
  2. What should I do so that it stays in setClientLoggingInResponse() and does only this memory.addToMemory(locationUuid, {})

NOTE: one thing that I have noticed that this error do not come immediately. But after sometime of deployment. But once it starts appearing it never disappears.

LOGS

2024-05-30 21:18:45 
{"level":100,"time":1717085925098,"pid":19,"hostname":"","msg":"preparing error response","method":"RequestProcessor.prepareErrorResponse"}
2024-05-30 21:18:45 
{"level":600,"time":1717085925098,"pid":19,"hostname":"","msg":"failed to process request","method":"RequestProcessor.process"}
2024-05-30 21:18:45 
{"level":400,"time":1717085925097,"pid":19,"hostname":"","msg":"memcache error: Server at kvs-memcached-client-logging:11211 not available while reading key=5c6c2ac0-1e7e-11ef-bc70-dba3d3ca35f7","method":"Client.<anonymous>"}
2024-05-30 21:18:45 
{"level":100,"time":1717085925097,"pid":19,"hostname":"","msg":"Data is not in memory for:","method":"ServiceToService.setClientLoggingInResponse"}
2024-05-30 21:18:45 
{"level":100,"time":1717085925097,"pid":19,"hostname":"","msg":"setClientLoggingInResponse","method":"ServiceToService.setClientLoggingInResponse"}

RequestProcessor Class

class RequestProcessor {
  static async process(requestOptions, tick = () => {}, ignoreAppKeyValidation) {

    const uniqueTimerIds = RequestProcessor.createUniqueTimerIds();
    _.set(requestOptions, 'uniqueTimerIds', uniqueTimerIds);

    try {

      tick('before RequestProcessor.callService...');
      await RequestProcessor.callService(requestOptions, tick);
      tick('after RequestProcessor.callService...');
      await RequestProcessor.setClientLoggingInResponse(requestOptions);
      RequestProcessor.prepareResponse(requestOptions);
    } catch (error) {
      logger.error('failed to process request', { error: error.message });
      RequestProcessor.prepareErrorResponse(requestOptions, error.message, error.errorCode);
    }

    LoggerStatus.tokenLogger(requestOptions, metrics);
  }

  static async callService(requestOptions, tick) {
    await serviceToService.callService(requestOptions, tick);
  }

  static prepareResponse(requestOptions) {
    logger.debug('preparing response', { payload: requestOptions.payload });
    serviceToService.prepareResponse(requestOptions);
  }

  static prepareErrorResponse(requestOptions, errorText, errorCode) {
    logger.debug('preparing error response', { errorText, errorCode, payload: requestOptions.payload });
    serviceToService.prepareErrorResponse(requestOptions, errorText, errorCode);
  }

  static async setClientLoggingInResponse(requestOptions) {
    await serviceToService.setClientLoggingInResponse(requestOptions);
  }
}

RequestProcessor.serviceToService = serviceToService;

module.exports = RequestProcessor;

ServiceToService Class

class ServiceToService {
  constructor() {
        // statments
  }

  async setClientLoggingInResponse(requestOptions) {
    const { payload } = requestOptions;
    logger.debug(`setClientLoggingInResponse`, payload);
    let cachedData = {};
    try {
      if (this.CLIENT_LOGGING_ENABLE && payload.access && payload.access.location && payload.access.location.uuid) {
        const locationUuid = payload.access.location.uuid;
        if (!memory.getFromMemory(locationUuid)) {
            logger.debug(`Data is not in memory for:`, locationUuid);
            const cacheKey = locationUuid;
            const timer = new Promise(resolve => setTimeout(resolve, this.CLIENT_LOGGING_MAX_READ_TIME_MS));
            const readFromCache = cache.readFromCache(cacheKey);

            const result = await Promise.race([timer, readFromCache]);
            
            if (result) { 
              logger.debug(`Won Race, Result found for:`, { locationUuid, result });
              try {
                cachedData = JSON.parse(result); 
                memory.addToMemory(locationUuid, cachedData)
                
              } catch (jsonError) {
                logger.info(`JSON decoding error: ${jsonError.message}`);
                cachedData = {};
                memory.addToMemory(locationUuid, cachedData)
              }
            }
            else
            {
              readFromCache.then(function(result)  //whenever response finishes after losing race condition with timer, store in memory the value as described below
              {
                logger.debug(`Lost Race, Result found for:`, { locationUuid, result });
                try {
                  cachedData = JSON.parse(result); // if result is not found (undefined) still catch will run and {} will store
                  memory.addToMemory(locationUuid, cachedData)
                } catch (jsonError) {
                  logger.info(`JSON decoding error: ${jsonError.message}`);
                  memory.addToMemory(locationUuid, {})
                }
              }).catch(function(e){
                  logger.info(`Error while reading memcache:`);
                  memory.addToMemory(locationUuid, {})
              });
            }
        }

        let obj = memory.getFromMemory(locationUuid); // need to make fresh call in case above process has set the object
        if (obj && Object.keys(obj).length > 0) {  // if object is not empty ({})
          logger.debug(`Found locationUuid=${locationUuid} in memory with value=`, obj);
          requestOptions.response._client_logging = obj;
        }
      }

    }
    catch(e)
    {
      memory.addToMemory(locationUuid, {}); // point 4 of spec IMPORTANT
      logger.debug(`Eception in setClientLoggingInResponse ${JSON.stringify(e)}`);
    }
  }
}

module.exports = ServiceToService;

MCache Class

const config = require('../config');
const Memcached = require('memcached');
const { logger } = require('logger-wrapper');
class MCache {
    constructor({ memcached }) {
      this.memcached = memcached;  
      this.readFromCache = this.readFromCache.bind(this);
      this.writeToCache = this.writeToCache.bind(this);
    }
  
    async readFromCache(key) {
      return new Promise((resolve, reject) => {
        this.memcached.get(key, (err, data) => {
          if (err) {
            logger.warning(`memcache error: ${err.message} while reading key=${key}`);
            reject(err);
          }
  
          resolve(data);
        });
      });
    }
  
    // other methods
  }

    const memcached = new Memcached(`${config.get('MEMCACHED_HOST')}:${config.get('MEMCACHED_PORT')}`);
    const mCache = new MCache({ memcached });

  module.exports = mCache;

Mysterious case of exception in nodejs

I am in dire need of help. I dont know when this error arises as I am unable to reproduce this bug on my own. Our center of attention is ServiceToService.setClientLoggingInResponse() method (which is called from RequestProcessor class line:12) . I have log printing the following output from bottom to top. We see memcache error on third logged statement. It occurs in MCache.readFromCache() method then it goes to catch block of RequestProcessor class (line 15 of RequestProcessor class). I am unable to comprehend why it is in catch block of RequestProcessor. Because I thought I have everything cover in setClientLoggingInResponse(). I thought if memcache error arises it should go to line 48 in setClientLoggingInResponse() method. But as log shows it didn’t. I have two questions.

  1. Why it didn’t end up in line 48 in setClientLoggingInResponse() method but rather end up in catch block (line 15 of RequestProcessor class)
  2. What should I do so that it stays in setClientLoggingInResponse() and does only this memory.addToMemory(locationUuid, {})

LOGS

2024-05-30 21:18:45 
{"level":100,"time":1717085925098,"pid":19,"hostname":"","msg":"preparing error response","method":"RequestProcessor.prepareErrorResponse"}
2024-05-30 21:18:45 
{"level":600,"time":1717085925098,"pid":19,"hostname":"","msg":"failed to process request","method":"RequestProcessor.process"}
2024-05-30 21:18:45 
{"level":400,"time":1717085925097,"pid":19,"hostname":"","msg":"memcache error: Server at kvs-memcached-client-logging:11211 not available while reading key=5c6c2ac0-1e7e-11ef-bc70-dba3d3ca35f7","method":"Client.<anonymous>"}
2024-05-30 21:18:45 
{"level":100,"time":1717085925097,"pid":19,"hostname":"","msg":"Data is not in memory for:","method":"ServiceToService.setClientLoggingInResponse"}
2024-05-30 21:18:45 
{"level":100,"time":1717085925097,"pid":19,"hostname":"","msg":"setClientLoggingInResponse","method":"ServiceToService.setClientLoggingInResponse"}

RequestProcessor Class

class RequestProcessor {
  static async process(requestOptions, tick = () => {}, ignoreAppKeyValidation) {

    const uniqueTimerIds = RequestProcessor.createUniqueTimerIds();
    _.set(requestOptions, 'uniqueTimerIds', uniqueTimerIds);

    try {

      tick('before RequestProcessor.callService...');
      await RequestProcessor.callService(requestOptions, tick);
      tick('after RequestProcessor.callService...');
      await RequestProcessor.setClientLoggingInResponse(requestOptions);
      RequestProcessor.prepareResponse(requestOptions);
    } catch (error) {
      logger.error('failed to process request', { error: error.message });
      RequestProcessor.prepareErrorResponse(requestOptions, error.message, error.errorCode);
    }

    LoggerStatus.tokenLogger(requestOptions, metrics);
  }

  static async callService(requestOptions, tick) {
    await serviceToService.callService(requestOptions, tick);
  }

  static prepareResponse(requestOptions) {
    logger.debug('preparing response', { payload: requestOptions.payload });
    serviceToService.prepareResponse(requestOptions);
  }

  static prepareErrorResponse(requestOptions, errorText, errorCode) {
    logger.debug('preparing error response', { errorText, errorCode, payload: requestOptions.payload });
    serviceToService.prepareErrorResponse(requestOptions, errorText, errorCode);
  }

  static async setClientLoggingInResponse(requestOptions) {
    await serviceToService.setClientLoggingInResponse(requestOptions);
  }
}

RequestProcessor.serviceToService = serviceToService;

module.exports = RequestProcessor;

ServiceToService Class

class ServiceToService {
  constructor() {
        // statments
  }

  async setClientLoggingInResponse(requestOptions) {
    const { payload } = requestOptions;
    logger.debug(`setClientLoggingInResponse`, payload);
    let cachedData = {};
    try {
      if (this.CLIENT_LOGGING_ENABLE && payload.access && payload.access.location && payload.access.location.uuid) {
        const locationUuid = payload.access.location.uuid;
        if (!memory.getFromMemory(locationUuid)) {
            logger.debug(`Data is not in memory for:`, locationUuid);
            const cacheKey = locationUuid;
            const timer = new Promise(resolve => setTimeout(resolve, this.CLIENT_LOGGING_MAX_READ_TIME_MS));
            const readFromCache = cache.readFromCache(cacheKey);

            const result = await Promise.race([timer, readFromCache]);
            
            if (result) { 
              logger.debug(`Won Race, Result found for:`, { locationUuid, result });
              try {
                cachedData = JSON.parse(result); 
                memory.addToMemory(locationUuid, cachedData)
                
              } catch (jsonError) {
                logger.info(`JSON decoding error: ${jsonError.message}`);
                cachedData = {};
                memory.addToMemory(locationUuid, cachedData)
              }
            }
            else
            {
              readFromCache.then(function(result)  //whenever response finishes after losing race condition with timer, store in memory the value as described below
              {
                logger.debug(`Lost Race, Result found for:`, { locationUuid, result });
                try {
                  cachedData = JSON.parse(result); // if result is not found (undefined) still catch will run and {} will store
                  memory.addToMemory(locationUuid, cachedData)
                } catch (jsonError) {
                  logger.info(`JSON decoding error: ${jsonError.message}`);
                  memory.addToMemory(locationUuid, {})
                }
              }).catch(function(e){
                  logger.info(`Error while reading memcache:`);
                  memory.addToMemory(locationUuid, {})
              });
            }
        }

        let obj = memory.getFromMemory(locationUuid); // need to make fresh call in case above process has set the object
        if (obj && Object.keys(obj).length > 0) {  // if object is not empty ({})
          logger.debug(`Found locationUuid=${locationUuid} in memory with value=`, obj);
          requestOptions.response._client_logging = obj;
        }
      }

    }
    catch(e)
    {
      memory.addToMemory(locationUuid, {}); // point 4 of spec IMPORTANT
      logger.debug(`Eception in setClientLoggingInResponse ${JSON.stringify(e)}`);
    }
  }
}

module.exports = ServiceToService;

MCache Class

const config = require('../config');
const Memcached = require('memcached');
const { logger } = require('logger-wrapper');
class MCache {
    constructor({ memcached }) {
      this.memcached = memcached;  
      this.readFromCache = this.readFromCache.bind(this);
      this.writeToCache = this.writeToCache.bind(this);
    }
  
    async readFromCache(key) {
      return new Promise((resolve, reject) => {
        this.memcached.get(key, (err, data) => {
          if (err) {
            logger.warning(`memcache error: ${err.message} while reading key=${key}`);
            reject(err);
          }
  
          resolve(data);
        });
      });
    }
  
    // other methods
  }

    const memcached = new Memcached(`${config.get('MEMCACHED_HOST')}:${config.get('MEMCACHED_PORT')}`);
    const mCache = new MCache({ memcached });

  module.exports = mCache;

Why is my React component not re-rendering after state update?

I am working on a React application and I am facing an issue where my component does not re-render after updating the state. I have a useState hook that I am using to manage the state, and I am updating the state inside an onClick event handler.

Here is the relevant code snippet:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
    console.log(count); // This logs the updated count correctly
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default Counter;

When I click the button, the count variable increments correctly (as shown in the console log), but the component does not re-render to display the updated count. What am I missing or doing wrong here?

What I’ve Tried
Ensured that setCount is correctly updating the state.
Checked the documentation for useState and useEffect hooks.
Tried forcing a re-render using a separate state variable.

Additional Context
I am using React 17.0.2.
The issue persists across different browsers.
There are no errors or warnings in the console.

Any insights or suggestions would be greatly appreciated!

Use pass-by-reference or better return? [closed]

As far I know primitive values (e.g. numbers, string, …) are passed by value.

mystr:string="abc";

chgstr (x:string)
{
    x = "xxx";
}

console.log (this.mystr);       // abc
this.chgstr (this.mystr);
console.log (this.mystr);       // abc -> no change!

Complex objects (e.g. objects, arrays) are passed by reference.

myobj:any={abc:123};
    
chgobj (x:any)
{
    x["abc"]="000";
}

console.log (this.myobj);       // Object {abc: 123}
this.chgobj (this.myobj);
console.log (this.myobj);       // Object {abc: 000} -> changed

Is it correct regarding programming guidlines to do so or is it recommended to return it anyway??

chgobj (x:any):any
{
    x["abc"]="000";
    return x;   // return!
}

myobj = this.chgobj (this.myobj);    // use the return-value

Issue with /poll command in Discord.js using ButtonStyle() + MongoDB poll data storage and recall

I have a Discord.js /poll slash command that is set up to store voting results on a MongoDB so that, if the application goes down for whatever reason, the voting states for any outstanding polls can be retrieved once the application goes back up. Or at least, that’s the goal. Here’s the issue I’m having with it:

I can start the application/bot node . logged as…

...Beep-boop...! R1N is on-line!
Connected to MongoDB Atlas

I can create the poll in Discord.

enter image description here

I can vote for the poll using the buttons on the resulting embed interaction, logging as this:

Interaction collected
Interaction ID: 1246188518967873631
Poll Data: {
  _id: new ObjectId('665a298062b1781646c29dd7'),
  messageId: '1246188518967873631',
  channelId: '1245054951084920902',
  guildId: '1117541797527293952',
  prompt: 'test',
  options: [
    {
      label: '1',
      emoji: '<:a_:1245594156890587137>',
      count: 0,
      voters: []
    },
    {
      label: '2',
      emoji: '<:b_:1245594145804779530>',
      count: 0,
      voters: []
    },
    {
      label: '3',
      emoji: '<:c_:1245594134253801513>',
      count: 0,
      voters: []
    }
  ],
  type: 'letters',
  showPercentage: true,
  multiChoice: false,
  anonymous: false,
  limit: 0
}
Options after fetching: [
  {
    label: '1',
    emoji: '<:a_:1245594156890587137>',
    count: 0,
    voters: Map(0) {}
  },
  {
    label: '2',
    emoji: '<:b_:1245594145804779530>',
    count: 0,
    voters: Map(0) {}
  },
  {
    label: '3',
    emoji: '<:c_:1245594134253801513>',
    count: 0,
    voters: Map(0) {}
  }
]
Selected Option: {
  label: '1',
  emoji: '<:a_:1245594156890587137>',
  count: 0,
  voters: Map(0) {}
}
Previous Votes: []
Selected Option after vote: {
  label: '1',
  emoji: '<:a_:1245594156890587137>',
  count: 1,
  voters: Map(1) { '590630085607030784' => '<@590630085607030784>' }
}
Options after vote: [
  {
    label: '1',
    emoji: '<:a_:1245594156890587137>',
    count: 1,
    voters: Map(1) { '590630085607030784' => '<@590630085607030784>' }
  },
  {
    label: '2',
    emoji: '<:b_:1245594145804779530>',
    count: 0,
    voters: Map(0) {}
  },
  {
    label: '3',
    emoji: '<:c_:1245594134253801513>',
    count: 0,
    voters: Map(0) {}
  }
]
Poll data updated in MongoDB

enter image description here

I can even unvote for my votes on the poll using the same buttons that show what I voted for. There is also supporting evidence in MongoDB that the voting results are being stored there during the session in which the poll was created.

However, when the app goes down Ctrl+C, and then I bring it back up again node ., the voting/unvoting no longer works correctly. It’s difficult to recreate the pattern of behavior at this point, but, if I voted for the poll before the restart, I seem to be able to click and click and click on that vote without it performing any changes to the poll embed… just ending each time after thinking about it with “This interaction failed.” If I then click on any other unvoted button, the application stops and logs this TypeError about my index.js:

              selectedOption.voters.set(i.user.id, `<@${i.user.id}>`);
                             ^

TypeError: Cannot read properties of undefined (reading 'voters')
    at InteractionCollector.<anonymous> (C:UserssnakeOneDriveDocumentsdiscordR1Nindex.js:92:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

If I hadn’t voted on the embed before the restart, I seem to get up to 3 failed clicks before the app goes down for the same reason.

I’ve been down the rabbit hole on this and have also tried using ChatGPT, Code Copilot (in ChatGPT), Github Copilot, and regular Copilot. No dice. They’ve only made the issue worse. This also serves to announce you may identify some needless code because of my adventures.