Enable SSE in AWS

I’m quite new to AWS, so I’m still learning stuff as I go.

I work on a project where we have multiple environments.
A while ago, I made some changes where I implemented some logic using ServerSentEvents in an Express.js server.

It was working excellent locally, but once I deployed my code to a test environment, the events were not sent anymore to the client, as they were blocked somehow. It took me a lot of time to find what the issue was, almost gave up to SSE, until finally I stumbled across an answer where that person was saying that there should be a setting enabled in AWS to allow the events to be sent.

Now, we have to launch another instance and I need to enable that setting again. The problem is I don’t remember at all where that setting was and I can’t find anything on the internet about this.

Could anyone show me where to find it in AWS Console? I’m going nuts right now!

Detect if PWA has been closed

im doing PWA app. How can i detect on frontend if user has closed my app? I do not mean keeping it in background. I want to invoke function on frontend when users close pwa from background processes. Something familiar to window.addEventListener('beforeunload',) but for PWA.

To be specific, i do have a chat app, i want to invoke LEAVE_ROOM socket emit when user has closed my app, i want to allow it work in background and being in queue(im sending user notification), but i want to leave queue when user closed app.

How can I render components dynamically with Vue 3?

I have a process which have many steps. Each one is implemented in a different component.

Initially I had this code:

<template>
  <template v-if="process.currentStep === 0">
    <Step0 />
  </template>
  <template v-else-if="process.currentStep === 1">
    <Step1 />
  </template>
  <template v-else-if="process.currentStep === 2">
    <Step2 />
      :
      :
</template>

<script setup>
import Step0 from "@/views/components/steps/step0.vue";
import Step1 from "@/views/components/steps/step1.vue";
import Step2 from "@/views/components/steps/step2.vue";
  :
  :

However, in order to make the code more readable, I tried to change to:

<template>
  <component :is="`Step${process.currentStep}`" />

But it doesn’t work.

I also tried:

<component :is="stepComponent" />

import { defineAsyncComponent } from 'vue';

const stepComponent = ref(); // Adjust the initial value as needed
const stepComponents = {
  Step0: defineAsyncComponent(() => import('@/views/components/steps/step0.vue')),
  Step1: defineAsyncComponent(() => import('@/views/components/steps/step1.vue')),
  Step2: defineAsyncComponent(() => import('@/views/components/steps/step2.vue')),
};

But neither get any result.

I don’t want to register these components in main.ts. Is there any way to do what I am trying to do?

Google Maps tiles not loading properly when Marker location significantly changes

I’m using @vis.gl/react-google-maps and React to create a Google Map. The parent component supplies a bunch of coordinates, which I apply to the map using new window.google.maps.LatLngBounds() and map.fitBounds() inside a useEffect. When the app sends a new set of coordinates, the useEffect creates a new instance of window.google.maps.LatLngBounds() and applies the bounds again.

For the most part this works fine, but if there is a significant change in location, say from Paris to somewhere in US, the tiles do not load properly.

Whatever I’ve searched on SO, the answers are quite old. There is also a workaround of adding the prop key={JSON.stringify(coordinateData)} that forces the map to re-render. But obviously that’s terribly inefficient, and I also lose the feature of the Map smoothly panning or zooming in to new locations.

import {
  AdvancedMarker,
  Map,
  useMap,
} from "@vis.gl/react-google-maps";

const MarkerWithInfoWindow = ({ activityData, position }) => {

return (
    <>
      <AdvancedMarker
        position={position}
        title={activityData.name}
      >
        <Image
           src={getActivityImgSrc(activityData)}
           width={36}
           height={36}
           alt={activityData.type}
        />
      </AdvancedMarker>
    </>
  );
};

export default function CustomMap({ displayData }) {
  const map = useMap();
  console.log('rerender map', displayData)

  useEffect(() => {
    if (!map || !displayData) return;


    const bounds = new window.google.maps.LatLngBounds();
    const { outdoorsData, travelData } = displayData;
    console.log(displayData);

    const yearsForFilter = new Set();

    for (var i = 0; i < outdoorsData.length; i++) {
      bounds.extend(
        new window.google.maps.LatLng(
          outdoorsData[i].coordinates.lat,
          outdoorsData[i].coordinates.lng
        )
      );
      yearsForFilter.add(new Date(outdoorsData[i].date).getFullYear());
    }
    for (var i = 0; i < travelData.length; i++) {
      for (var k = 0; k < travelData[i].coordinatesArray.length; k++) {
        bounds.extend(
           new window.google.maps.LatLng(
              travelData[i].coordinatesArray[k].lat,
              travelData[i].coordinatesArray[k].lng
           )
        );
      }
      if (travelData[i].startDate) {
         yearsForFilter.add(new Date(travelData[i].startDate).getFullYear());
      }
    }

    map.fitBounds(bounds);

  }, [map, displayData]);

return (
    <Map
        mapId="DEMO"
        defaultZoom={2}
        defaultCenter={{ lat: 5.145259, lng: -27.8719489 }}
        mapTypeControl={false}
        streetViewControl={false}
    // key={JSON.stringify(displayData)}
    >
        {displayData.outdoorsData.map((activityData, index) => {

            return (
                <MarkerWithInfoWindow
                    key={index}
                    activityData={activityData}
                    position={{
                        lat: activityData.coordinates.lat,
                        lng: activityData.coordinates.lng,
                    }}
                />
            );
        })}
        {displayData.travelData.map((activityData) => {
            return activityData.coordinatesArray.map((coordinatesObj, index) => {
                return (
                    <MarkerWithInfoWindow
                        key={index}
                        activityData={activityData}
                        position={{ lat: coordinatesObj.lat, lng: coordinatesObj.lng }}
                    />
                );
            });
        })}
    </Map>
);

};

Tiles not loading properly

Can you explain React’s rendering lifecycle and make sense why “Layout Rendered” is logged before rendering any of the JSX Components?

Layout

Navbar

Home

Console

I was trying to understand the lifecycle of a React functional component and I added some logs in the parent component to check if it renders before the children. Turns out any JS function called inside return is executed and then the JSX components and their content is rendered. Could anyone explain why that is?

Note that the 2 logs from Navbar between Layout rendering and Layout rendered is from the Navbar function call, while other functional JSX components are rendered later.

How to pass a axios response to a function

I try this code and get an infinite loop

request.jsx

import { useEffect, useState } from 'react';
import axios from 'axios';

export async function getCategories() {
    const [categories,setCategories]= useState();
    try {
       await useEffect(() => {
            axios.get("http://localhost:3001/api/req/categories",).then(function (res) {
                const response = JSON.stringify(res.data)
                setCategories(response);
            });
    
            
   
    
        }, [])
            return categorias;
    } catch (error) {
        console.log(error);
    }

}

item_new.jsx


import { getCategories } from ".request";
import { useEffect, useState } from "react";
const [categorieSelect, setCategorieSelect] = useState();

getCategories().then(response => {
    
    try {
      const res = JSON.parse(response);
     
      setCategorieSelect(res)

    } catch (error) {
      console.log(error)
    }
 console.log(categorieSelect)  // infinite loop
  })

I also try to put a useEffect and get this error

react-dom.development.js:15408 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.<

import { getCategories } from ".request";
import { useEffect, useState } from "react";
const [categorieSelect, setCategorieSelect] = useState();

getCategories().then(response => {
    
    try {
      useEffect(()=>{   
      
       const res = JSON.parse(response);
       setCategorieSelect(res)

   },[])
   

    } catch (error) {
      console.log(error)
    }
 console.log(categorieSelect)  // infinite loop
  })

Why does npm install spawn exponentially greater numbers of processes?

I have a number of JavaScript packages hosted in private GitHub repositories. I’ve found that the more of those packages I include as dependencies the more processes npm install spins up. This is getting to the point where a single run of npm install eats all 16 CPU cores, spawns hundreds of npm install processes, and takes hours to complete, if it does not fail altogether.

This image shows some of the packages I have authored and am using and the way in which they depend on one another:

Dependency Tree

  • Running an install at the Node level takes about 6 seconds and spawns no additional processes.
  • Running an install at the Lambda level takes about 13 seconds and spawns 3 additional processes.
  • Running an install at the Entity level takes about 3 minutes and spawns 22 additional processes.
  • Running an install at the Core level takes about 26 minutes and spawns at least 150 additional processes (some complete before others spawn, so it is difficult to get an exact count).
  • Running an install in a project that includes the Core package takes about 2 hours and spawns hundreds of additional processes.

I am running Node 20.18.0 with NVM 0.39.1.

My private dependencies are specified in the package.json dependencies section in the format:

"package-name": "github:username/repo.name#semver:X.X.X"

I have no problems with authentication and retrieving the packages is very fast. The issue seems to occur after the packages have been downloaded.

The Util and Test packages are ES modules, the rest are CommonJS2.

I’ve deleted the package-lock.json files and node_modules directories and tried running a fresh install.

I’ve tried installing the private dependencies one by one.

I have tried some hacky methods to try to determine the underlying cause, such as bundling the lower level dependencies using webpack and changing the private dependencies to dev-dependencies.

I’ve also tried using yarn, but it has the same problem.

Project is not receiving data from API

My project is supposed to display products from an API that I hosted on Github Pages. I used vanilla javascript to create the code. Here it is:

import { allProductsUrl } from "./utils.js";

const fetchProducts = async () => {
  const response = await fetch(allProductsUrl).catch((err) => console.log(err));
  if (response) {
    return response.json();
  }
  return response;
};

export default fetchProducts;

When I inspected the browser, I wanted an error message to show up in the console. Unfortunately, there is no error message when going into inspect mode. Even if I change the console log to a simple string message I’m still not getting any results within the console. Here is the code where I choose to invoke the function that I created:

import "./src/toggleSidebar.js";
import "./src/cart/toggleCart.js";
import "./src/cart/setupCart.js";
// specific imports
import fetchProducts from "./src/fetchProducts.js";
import { setupStore, store } from "./src/store.js";
import display from "./src/displayProducts.js";
import { getElement } from "./src/utils.js";

const init = async () => {
  const products = await fetchProducts();
  if (products) {
    // add products to the store
    setupStore(products);
    const featured = store.filter((product) => product.featured === true);
    display(featured, getElement(".featured-center"));
  }
};

window.addEventListener("DOMContentLoaded", init);

I’ve tested my API on Postman and I received a response. Please let me know how I can get a response within my project.

How to set AppKit (Web3Modal) provider for web3.js?

Dear smart contract front-end developers,

As you know, AppKit is the new verion of Web3Modal. I am using it in a web javascript program to show a dialog to connect the web page to the desired wallet. Then I want to use Web3.js to interact with some smart contracts.

So I use this program:

import { createAppKit, ReownAppKitModal } from '@reown/appkit'
import { bsc } from '@reown/appkit/networks'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { reconnect } from '@wagmi/core'
import { Web3 } from 'web3'
import { useAppKitProvider, useAppKitAccount } from "@reown/appkit/react";

const projectId = '...'
const networkList = [ bsc]
const wagmiAdapter = new WagmiAdapter({
    projectId,
    networks: networkList
})
const metadata = {
    name: '...',
    description: '...',
    url: 'https://...',
    icons: ['...'],
};
const modal = createAppKit({
    adapters: [wagmiAdapter],
    networks: networkList,
    projectId,
    metadata: metadata,
    themeMode: 'light'
})
reconnect(wagmiAdapter.wagmiConfig)
const { walletProvider } = useAppKitProvider();
console.log(walletProvider);
const web3 = new Web3(xxx);

Now I want to use a Web3 provider instead of xxx in the last line of the above program.

For example if I use window.ethereum it works only if I use Metamask wallet.

What can I use instead of Web3 provider so it connects to the wallet that selected in AppKit modal dialog?

I will appreciate you, even if you give a solution in Web3Modal.

heading and list don’t work No change is made by clicking in ckEditor5 , next js14

I have a problem using ckEditor in nextjs14…
I have done according to the document and I have done the settings according to the code I have written
see output image

i have use @ckeditor/ckeditor5-react & ckeditor5

I expect it to be numbered when I click on a numbered list, or enlarged when I select a word and click on Heading.

 <CKEditor
            editor={ ClassicEditor }
            config={ {
                toolbar: {
                    items: [
                        'undo',
                        'redo',
                        '|',
                        'heading',
                        '|',
                        'fontSize',
                        'fontFamily',
                        '|',
                        'bold',
                        'italic',
                        'underline',
                        'strikethrough',
                        'removeFormat',
                        '|',
                        'link',
                        'insertImage',
                        'ckbox',
                        'mediaEmbed',
                        'insertTable',
                        'highlight',
                        'blockQuote',
                        '|',
                        'alignment',
                        '|',
                        'bulletedList',
                        'numberedList',
                        'multiLevelList',
                        '|',
                        'accessibilityHelp'
                    ]
                },
                plugins: [
                    Alignment,
                    Autoformat,
                    AutoLink,
                    Autosave,
                    BlockQuote,
                    Bold,
                    FontSize,
                    FontFamily,
                    Heading,
                    Highlight,
                    Image,
                    ImageCaption,
                    ImageResize,
                    ImageStyle,
                    ImageToolbar,
                    ImageUpload,
                    Italic,
                    Link,
                    List,
                    MediaEmbed,
                    Mention,
                    Paragraph,
                    PasteFromOffice,
                    PictureEditing,
                    RemoveFormat,
                    Strikethrough,
                    Table,
                    TableCaption,
                    TableCellProperties,
                    TableColumnResize,
                    TableProperties,
                    TableToolbar,
                    Underline,
                    Undo,
                ],
                heading: {
                    options: [
                        {
                            model: 'paragraph',
                            title: 'Paragraph',
                            class: 'ck-heading_paragraph'
                        },
                        {
                            model: 'heading1',
                            view: 'h1',
                            title: 'Heading 1',
                            class: 'ck-heading_heading1'
                        },
                        {
                            model: 'heading2',
                            view: 'h2',
                            title: 'Heading 2',
                            class: 'ck-heading_heading2'
                        },
                        {
                            model: 'heading3',
                            view: 'h3',
                            title: 'Heading 3',
                            class: 'ck-heading_heading3'
                        }
                    ]
                },
                image: {
                    toolbar: [ 'imageTextAlternative', '|', 'ckboxImageEdit' ]
                },
                initialData: '<p>Hello from CKEditor 5 in React!</p>'
            } }
        />

How to display name values for numerical enum in Vue? [duplicate]

I am building a little vue.js webapp tool to view and edit a backend config file (formatted as a json). The object has an enum field which is represented on the backend as a uint, but I would like to somehow map the display name to the numerical value in the json and then display the options in a dropdown select. I currently have a v-for element that loops over each config record and displays each field.

The object looks like:

{records:[
  {
    id:"12345",
    target:678,
    src:"path/to/src"
    operator:0 // backend enum where values 0,1,2... map to the below operators
  },
  ... // more records
}

I currently have the following for the dropdown:

<label class="recorditem">Comparison Operator:
  <select v-model="record.operator">
    <option>EQ</option>   // should map to 0
    <option>NEQ</option>  // should map to 1
    <option>GT</option>   // should map to 2
    <option>GTE</option>  // should map to 3
    <option>LT</option>   // should map to 4
    <option>LTE</option>  // should map to 5
  </select>
</label>

Is there any way to take the numerical value in the json and with javascirpt/vue display the text “EQ”, “NEQ”, etc. in the dropdown on the webpage and then when the user clicks on the selected option in the dropdown, have it update the data with the numerical value (instead of the text) as defined by the backend?

EDIT: I deleted a section of code that displayed how the backend was generating the json and why it’s an enum but that somehow got the question marked as a duplicate so it is now removed.

Why does my JavaScript promise chain return undefined despite having a return statement? [closed]

 function fetchData() {
return fetch('https://api.example.com/data') // Replace with a real API endpoint
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json(); // Parse the JSON data
    })
    .then(processedData => {
        console.log("Processed Data:", processedData);
        return processedData; // Return the processed data
    })
    .catch(error => {
        console.error("An error occurred:", error);
        throw error; // Propagate the error
    });

}
Function Documentation:
Added a function-level comment to explain its purpose and return type. This makes it easier for other developers to understand the function.

Error Handling:

Used if (!response.ok) to explicitly check for HTTP response status errors (e.g., 404, 500).
Added a descriptive error message using throw new Error().
Data Transformation:
In the second .then() block, data is processed further, such as extracting important fields and adding a timestamp. This is a common use case for APIs that return large JSON objects.

Comments for Clarity:
Inline comments explain what each part of the code does. This helps make the code easier to follow for beginners.

Reusable Design:
By returning a Promise, this function can be reused in other parts of your application for API requests.

Error Propagation:
Errors are logged and re-thrown so the calling code can handle them. This ensures robust error handling at every level.

MVC framework for javascript instead of asp.net

I have to do MVC structure website for school project and I have some experience with react and next.js. We are doing it in asp.net but I am not good with C# so I want to use javascript. I tried sails js but I am having tough time with it but unfortunately it didn’t connect foreign keys in database that I need and my teacher didn’t like that. The only requirment for the project is that it has to be done in MVC structure so I want to know. Is there any way to make Next.js into MVC like structure so it will be good for the project? If not is there any good js framework with MVC structure that I can learn fast? (I have about 3-4weeks and database is already done in sql) There has to be migration to database with models. There has to be some roles so for example admin can see page in views where are all users and can edit their rights but user can’t see that page.

I tried to use sails.js but it doesn’t work as I wanted

How to reproduce horizontal flow layout as custom layout in embed.diagrams.net / draw.io?

I would like to programmatically trigger a layout operation for diagrams.net.

I would like to use the horizontal flow layout that is available in the ui and as style:

style="childLayout=flowLayout;flowOrientation=west;"

However, for the api there is no type mxFHorizontalFlowLayout.

=> How to reproduce the horizontal flow layout specified as style, based on the supported layout types?

=> Or how can I trigger an update of the layout, based on the already specified style? (Unfortunately, draw.io does not apply the style automatically but only after manual edits.)

I tried to use mxHierarchicalLayout but I get different results.

        /* available layouts:
        https://www.drawio.com/doc/faq/apply-layouts#custom-layouts

        0 : "mxHierarchicalLayout"
        1 : "mxCircleLayout"
        2 : "mxCompactTreeLayout"
        3 : "mxEdgeLabelLayout"
        4 : "mxFastOrganicLayout"
        5 : "mxParallelEdgeLayout"
        6 : "mxPartitionLayout"
        7 : "mxRadialTreeLayout"
        8 : "mxStackLayout
        */

   function sendLayoutMessage() {{
        // tries to apply a horizontal flow layout
        console.log('layout');
        var iframe = document.getElementById('drawio-iframe');
        var layoutMessage = JSON.stringify({{
            action: 'layout',
            layouts: [
                {{
                    "layout": "mxHierarchicalLayout",
                    "config": {{
                      "orientation": "west",
                      "intraCellSpacing": 0.1,
                      "interRankCellSpacing": 0.1,
                      "interHierarchySpacing": 0.1,
                      "parallelEdgeSpacing": 0.1
                    }}                       
                }}
            ]
        }});
        iframe.contentWindow.postMessage(layoutMessage, '*');
    }}