Mapping components dynamically using webpack in Next.js

I’m building a NextJS app which fetches data from a strapi CMS at build time. Strapi allows to organize content using components and I would like to map strapi components to the ones of my Next project in order to build each web page according to the data fetched from strapi.

I would like, though, to keep my code clean and export a variable named strapiComponentId from each module that also exports a component (as a default export) in order to construct my component mapping at build time.

I was able to achieve this by using webpack’s require.context feature as follows

const req = require.context("@/components", false, /components.*.js$/);

const mapping = req.keys().reduce((acc, current) => {
  const module = req(current);
  if (module.strapiComponentId != undefined) {
    acc[module.strapiComponentId] = module.default;
  }
  return acc;
}, {});

This way I have a map that, given a strapi component id (which is part of the strapi response), returns the related component. The code does not handle errors but works for testing purposes.

In order for the req(current) function to return an object instead of a promise I had to set experimental: { esmExternals: false } in next.config.js, as stated here.

My question is, then, the following:

Is there better solution in order to achieve the same result (maybe using next/dynamic feature)? If not, which are the side effects caused by disabling esmExternals?

Thank you for your time.

jquery arrays matrices with html

What I want to do is that when the user asks for the number of arrays that the code must have, the relevant tables and arrays are automatically generated, in order to achieve this if you can help me so that I can come to understand how Could I do this for a company?

<script>
$(document).ready(function() {

  // let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  // let matriz =[array, array];

  // function arrays(array) {
  //     let resultado = 0;
  //     for (let i = 0; i < array.length; i++) {
  //         console.log(array[i]);
  //         $("#div1").append(array[i]);
  //         array[i] = array[i] * 7;
  //         resultado += array[i] * 7;
  //     }
  //     console.log("array por 7 "+resultado);
  // }
  // arrays(array);

  let tabla = "<table>";
  tabla += " <tr>";
  tabla += "<td id='4_1'>4-1</td>";
  tabla += "<td id='4_2'>4-2</td>";
  tabla += "<td id='4_3'>4-3</td>";
  tabla += "<td id='4_4'>4-4</td>";
  tabla += " </tr>";
  tabla += " <tr>";
  tabla += "<td id='3_1'>3-1</td>";
  tabla += "<td id='3_2'>3-2</td>";
  tabla += "<td id='3_3'>3-3</td>";
  tabla += "<td id='3_4'>3-4</td>";
  tabla += " </tr>";
  tabla += " <tr>";
  tabla += "<td id='2_1'>2-1</td>";
  tabla += "<td id='2_2'>2-2</td>";
  tabla += "<td id='2_3'>2-3</td>";
  tabla += "<td id='2_4'>2-4</td>";
  tabla += " </tr>";
  tabla += " <tr>";
  tabla += "<td id='1_1'>1-1</td>";
  tabla += "<td id='1_2'>1-2</td>";
  tabla += "<td id='1_3'>1-3</td>";
  tabla += "<td id='1_4'>1-4</td>";
  tabla += " </tr>";
  tabla += "</table>";
  $("#div1").append(tabla);

  let filas = $("#filas");
  let columnas = $("#columnas");

  let arrayfila = [];
  let valorpiso = 100000;
  let incremento = 0;
  for (let x = 0; x < filas; x++) {
    let arraycolumnas = [];
    for (let y = 0; y < columnas; y++) {
      incremento = x + 1;
      //  let array0 = [100.000,100.000,100.000,100.000];
      arraycolumnas[y] = valorpiso;
    }
    valorpiso = valorpiso + 100000;
    arrayfila[x] = arraycolumnas;
  }

  $("td").click(function() {
    let x = $("#" + this.id).text().split("-")[0] - 1;
    let y = $("#" + this.id).text().split("-")[1] - 1;
    console.log("La posición x  del array es " + x + " y la de la y es " + y + " y su precio es " + arrayfila[x][y]);
    let deuda = parseInt($("#deuda").val());
    deuda = deuda + arrayfila[x][y];
    $("#deuda").val(deuda);
    console.log(deuda);
  });
});
</script>

Hi, I have a problem. Let’s see if you can solve it, I’m working with matrices and what I want is for the user to request the number of arrays he wants. How can I do it?

Print javascript loop to tag id

The same output I get in a console.log is not posting to the html div and i cannot figure out why?

typconst myLibrary = ["Theif", "The Lion", "Harry Potter", "Lord of the Rings"];

function Book(){
    // the constructor
}

var bookLength = myLibrary.length;


function addBookToLibrary() {
    for (var b = 0; b < bookLength; b++)
        console.log(myLibrary[b]);
        return myLibrary[b];        
}

var labels = document.getElementById("myBooks").innerHTML;
labels = addBookToLibrary();

<body>

    <p>My list should be below</p>
    <p id="myBooks"></p>

    <script src="script.js"></script>

</body>``

I am expecting this array to print const myLibrary = [“Theif”, “The Lion”, “Harry Potter”, “Lord of the Rings”];

Smarter way of chaining SVG operations in this example?

In the following code, I create text svg elements, word-wrap it and then create bounding boxes based on the new (wrapped) text dimensions and recntagles. I was only able do it in the following way, and I would like to know if the code could not be simplified so that maybe the boxes are created in the same function as the text?

 var a=settings.g.selectAll(".axislabel")
                .data(featureData)
                .join(
                    enter => enter.append("text")
                        .attr("x", d => d.label_coord.x)
                        .attr("y", d => d.label_coord.y)
                        .text(d => d.name)
                        .attr("dy", "0.35em")
                        .call(wrap, 60)
                )
    
    var x=settings.g.selectAll("text")
/getting the elements I just created
    for(let a of x['_groups'][0])
    {
        //iterating through and create bounding boxes
        var v=a.getBBox();
       //createing rectangles based on the boundinx boxes
        settings.g.selectAll("labelBack")
        .data([a.textContent])
        .join(
            enter => enter.append("rect")
                .attr("x", v.x)
                .attr("y", v.y)
                .attr("width", v.width)
                .attr("height", v.height)
                .attr("fill", "white")
                        .attr("opacity", 1)
                        .attr("stroke-width", 1)
                        .attr("stroke", "black")
        );

Rotate element on Google Map relative to map not div

I’m working on project using Google Maps API and I’m stuck on some feature, which I want to do.
On my map I have div which should point to certain place on map. I’m able to compute all angles and distances but I have problem with rotating this “pointer”.

I’m using computeHeading function which gives me angle related to north pole. But when I’m applying this angle to my div transform property it’s not accurate because it’s not related to map container.

Example:

this.heading = google.maps.geometry.spherical.computeHeading(mapCenter,destinationPoint);

give result about 81 degrees but on the screen is 90 degrees.

Closer the two points are, the difference is smaller but this still occurs.

Does someone has any idea how to convert this angles?

How can I locally override a source-mapped JavaScript file in Chrome DevTools?

I have a bundle of minified JavaScript files (created with babel) along with a source map file. I can use the source map to add break points and step through the original code. What I’d like to do now is to create a local override of the original code in order to test some changes.

As I understand the process of debugging with a source map, the browser is executing the minified code from the bundle and mapping it to the original code as a convenience for debugging. My attempts to override the original file seem to confirm this. No matter what I do to the original file, I can clearly demonstrate that the minified code from the bundle is executed. So it seems like any local override is not possible – is there anyway around this?

“Migrations” hit an invalid opcode while deploying

I have suddenly started getting ‘”Migrations” hit an invalid opcode while deploying’ error when I do ‘truffle deploy’ command.

My migrations file has not changed so I’m not sure why I am suddenly getting this error. Everyone who’s posted for the same error just suggests downloading latest versions of ganache/truffle but I have updated my truffle and ganache to the most up to date versions and still getting the error.

This is the full error:
⠋ Fetching solc version list from solc-bin. Attempt #1
Starting migrations…

Network name: ‘development’
Network id: 5777
Block gas limit: 6721975 (0x6691b7)

1_initial_migration.js

⠙ Fetching solc version list from solc-bin. Attempt #1
Deploying ‘Migrations’

*** Deployment Failed ***st from solc-bin. Attempt #1

“Migrations” hit an invalid opcode while deploying. Try:

  • Verifying that your constructor params satisfy all assert conditions.
  • Verifying your constructor code doesn’t access an array out of bounds.
  • Adding reason strings to your assert statements.

Exiting: Review successful transactions manually by checking the transaction hashes above on Etherscan.

Error: *** Deployment Failed ***

“Migrations” hit an invalid opcode while deploying. Try:

  • Verifying that your constructor params satisfy all assert conditions.
  • Verifying your constructor code doesn’t access an array out of bounds.
  • Adding reason strings to your assert statements.
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:330:1

Truffle v5.9.2 (core: 5.9.2)
Node v18.7.0

Migrations.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

contract Migrations {
    address public owner;
    uint256 public lastCompletedMigration;

    constructor() {
        owner = msg.sender;
    }

    modifier restricted() {
        require(msg.sender == owner, "Restricted to contract owner");
        _;
    }

    function setCompleted(uint256 completed) public restricted {
        lastCompletedMigration = completed;
    }

    function upgrade(address new_address) public restricted {
        Migrations upgraded = Migrations(new_address);
        upgraded.setCompleted(lastCompletedMigration);
    }
}

1_initial_migration.js

const Migrations = artifacts.require("Migrations");

module.exports = function(deployer) {
    deployer.deploy(Migrations);
};

“Error: Duplicate entry ’16’ for key ‘contato.PRIMARY'” [closed]

Estou desenvolvendo uma api no Node-Red mas estou com um erro “Error: Duplicate entry ’16’ for key ‘contato.PRIMARY'”.
Esse é o código:

let id = msg.req.params.id;
let nome = msg.req.params.nome;
let telefone = msg.req.params.telefone;

msg.topic = `UPDATE contato SET n_contato_contato="${id}" ,s_nome_contato="${nome}",            s_wpp_contato="${telefone}" `;
return msg;

aparentemente eu não consigo atualizar um contato no banco de dados com a mesma chave(id) que ele já possui. como resolvo?

Next.js: app directory responses always return a 500 response

I’m making an endpoint in next.js. All my bindings to postgres complete successfully, errors are caught and so on. When i make requests using the fetch API in another tab or postman the NextResponses are not sent and a HTTP 500 is always recieved without the body of the request that i’ve sent.

If this is relevant, this is in the callback of an asynchronous bcrypt hash.

        const query: QueryConfig = {
            text: "INSERT INTO user_accounts(username, hash) VALUES($1, $2)",
            values: [username, hashedPassword]
        }
        try {
            await pool.query(query);
            return NextResponse.json({ success: true });
        } catch (err) {
            console.error(err, "nnERROR CAUGHT");
            return NextResponse.json({ success: false })
        }

Converting XML to Array in Javascript

Parse XML to array using Javascript

I tried the below code and it worked fine.

    var response = '<?xml version="1.0" encoding="UTF-8"?><root><node1>something</node1></root>'  

var xmlDoc = $.parseXML( response );

var myArray = getXMLToArray(xmlDoc);

alert(myArray['root']['node1']);
//Pop up window displaying the text "something"

function getXMLToArray(xmlDoc){
    var thisArray = new Array();
    //Check XML doc
    if($(xmlDoc).children().length > 0){
    //Foreach Node found
    $(xmlDoc).children().each(function(){    
        if($(xmlDoc).find(this.nodeName).children().length > 0){
        //If it has children recursively get the inner array
        var NextNode = $(xmlDoc).find(this.nodeName);
        thisArray[this.nodeName] = getXMLToArray(NextNode);
        } else {
        //If not then store the next value to the current array
        thisArray[this.nodeName] = $(xmlDoc).find(this.nodeName).text();
        }
    });
    }
    return thisArray;
}

But I am getting Invalid XML error if I pass xml from PHP Curl instead of response variable.

Unable to launch iPhone Simulator with Titanium app

When trying to run the iPhone simulator for my Titanium app, I get the following error:

[ERROR] WWDR Intermediate Certificate not found

Download and install the certificate from https://www.apple.com/certificateauthority/AppleWWDRCAG2.cer

Even after downloading and installing the certificate in my keychain app, the error persists.

I found someone else asked about this issue a few months ago, and the response was, “a fix was pushed to the SDK itself so the link will be fixed in the next release.”

WWDR Intermediate Certificate not found Error – IOS Simulator Launch Issue

However, since that response was posted, I downloaded Titanium SDK 12.1.1.GA, and the error persists. When I looked at GitHub to see what was included in the fix, there were only two changes to the source code, which look like changes to output messages about the correct URL to use for downloading the certificate. Nothing looked like it actually fixed the search for the correct certificate.

https://github.com/tidev/titanium-sdk/pull/13747

Is there anything I can do to fix this issue?

Sending an audio file to .net webapi from Next.js

I am building an upload service into my Next.js application where people can upload music.
Everything works to plan until i have to send the file to my .net webapi. The weird thing is that i am sending a valid FormData file with the right headers, still my IFormFile stays null everytime i make a post request to upload.

Next.js component:

import React, { useState } from 'react'
import { useUser } from '@auth0/nextjs-auth0/client'
import { ChevronDownIcon } from '@heroicons/react/24/outline';
import axios from 'axios';

function MyMusic({token}) {

    const { user, error, isLoading } = useUser();
    const [selectedFile, setSelectedFile] = useState(null);

    const handleFileChange = (event) => {
        const file = event.target.files[0];
        setSelectedFile(file)

        console.log(selectedFile);
    };

    const handleUpload = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('audio', selectedFile);
       
        try {
            const response = await axios.post('/api/upload/postUpload', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
              },
            });
        
            console.log(response.data);
          } catch (error) {
            console.error('Error uploading audio file:', error);
          }
    } 

    return (
        <div className="flex-grow text-white">

        <header className="absolute top-5 right-8">
            
            {
                (user &&
                    <div className="flex items-center bg-black space-x-3 opacity-90 hover:opacity-80 cursor-pointer rounded-full p-1 pr-2">
                        <img className="rounded-full w-10 h-10" src={user.picture} alt=""/>
                        <h5>{user.name}</h5>
                        <ChevronDownIcon className="h-5 w-5" />
                    </div>
                )
            }
            
        </header>

        <section className={"flex items-end space-x-7 bg-gradient-to-b to-black from-purple-500 h-80 text-white padding-8"}>
            
        </section>

        <div class="flex flex-col items-center justify-center text-white">
            <h1 className='flex font-bold text-2xl pb-5'>Upload your podcast</h1>

            <div class="w-full max-w-xs">
                <form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" enctype="multipart/form-data">
                    <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
                        File
                    </label>
                    <input class="shadow border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline" type="file" name="file" placeholder="file" onChange={handleFileChange}/>
                    </div>

                    <button class="flex items-center space-x-2 bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-full" onClick={handleUpload}>
                        Upload
                    </button>
                </form>
                
            </div>

            
        </div>
    </div>
    )
}

export default MyMusic

When i make the call to the Next.js server-side api i retrieve the file with Formidable. Then i put the file in a FormData and send it to my webapi.

Server-side api:

import formidable from "formidable";

export const config = {
    api: {
        bodyParser: false,
    }
}

export default async function handler(req, res) {

    if (req.method !== 'POST') {
        res.status(405).json({ error: 'Method Not Allowed' });
        return;
    }
    
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
    if (err) {
        console.error('Error parsing form data:', err);
        res.status(500).json({ error: 'Internal Server Error' });
        return;
    }
    // Access the uploaded file
    const audioFile = files.audio;

    uploadFile(audioFile);
    
    res.status(200).json({ message: 'Message uploaded!' });

    });
}

async function uploadFile(audioFile) {

    const form = new FormData();
    form.append('file', audioFile);

    console.log(form);
    const response = await fetch('http://localhost:5222/api/Values/upload', {
        method: 'POST',
        headers: {
            "Content-Type": "multipart/form-data"
        },
        body: form,
    });
}

This is the output of the console.log(form):

FormData {
  [Symbol(state)]: [
    {
      name: 'file',
      value: 'PersistentFile: 6e3e4777a88ff2649a0040400, Original: nelk_pod_export (1).wav, Path: /var/folders/m7/jxmplnsd7t74s8cy1fxfc1bw0000gn/T/6e3e4777a88ff2649a0040400'
    }
  ]
}

After this my IFormFile in my webapi stays null. I have no idea what i am doing wrong, i asked ChatGPT but no success, i read multiple articles and tutorial but also no success, i hope someone can tell me what i am doing wrong. This shouldn’t be such a pain to accomplish.

If i upload a file through swagger, it works fine.

javascript: How to create a multidimensional array from a json

I need to generate a multidimensional array from the below json structure. The catch here is current json have duplicate values in each key-value pairs, when new multidimensional array is created each duplicated item should be paired duplicate of each other as mentioned below.

{
  1001: ["Choco Chip Muffin", "Choco Chip Muffin", "Espresso", "Espresso", "Espresso" ],
  1002: ["veg puff", "Brownie Fondente","veg puff", "veg puff"]
}

output looking for

{
  1001: [["Choco Chip Muffin","Espresso"],["Choco Chip Muffin","Espresso"], ["Espresso"]],
  1002: [["veg puff", "Brownie Fondente"],["veg puff"], ["veg puff"]],
}

Is there a way that won’t trigger a pop up blocker on chrome and edge when using window.open on javascript on a new tab?

I’m trying to used this function:

 Page.ClientScript.RegisterStartupScript(Me.GetType(),
                     "PrintReportScript",
                     "window.open('" & GlobalConstants.REPORT & "', '_blank');",True)

but this one triggers popup blocker. Is there anyway I could prevent it? Or perhaps a different approach of opening a new tab without triggering the popup blocker?

Discord.js detect double boost and boost cancellation

Im trying to make a discord bot that is capable of detecting when someone boosts a server multiple times and when someone cancells one of their boosts.

The issue im currently facing is that there is no offical documentation on detecting multiple boosts. Ive attempted to use the guildMemberUpdate event however the member update is only updated after an intial boost and no follow up boosts.

The only way to possibly detect a double boost is by listening for a boost message

However how do I detect if one of the boosts is cancelled ?

Since there isnt an update event called