Node.JS migration to 18.14.1 version issue: error:0308010C:digital envelope routines::unsupported

I have migrated from node.js 16.15.0 to 18.14.1.

Right now, I am having an error coming from babel-loader.js in a custom framework (just FYI for the react based advice) :

enter image description here

This is what I am having in the place where issue is coming:

var filename = function filename(source, identifier, options) {
  var hash = crypto.createHash("md4");
  var contents = JSON.stringify({
    source: source,
    options: options,
    identifier: identifier
  });

  hash.update(contents);

  return hash.digest("hex") + ".json.gz";
 };

As I understand, the origin of the issue comes from Webpack using the MD4 algorithm in its build process, which is no longer supported in the latest Node.js version. So I have updated the webpack version to 5.75.0 (doesn’t help at all) and also I decided to patch the babel-loader dependency, by switching the algorithm from md4 to md5:

var filename = function filename(source, identifier, options) {
  var hash;
  try {
    hash = crypto.createHash("md4");
  } catch (e) {
    console.warn('Crypto "md4" is not supported anymore by this Node version');
    hash = crypto.createHash("md5");
  }
  var contents = JSON.stringify({
    source: source,
    options: options,
    identifier: identifier
  });

  hash.update(contents);

  return hash.digest("hex") + ".json.gz";
};

I am not having this error anymore, BUT the content is not being rendered and I am having a lot of issues in the console. I believe it’s because I changed the way of hashing, but I also have to do the proper un-hashing in babel-loader.js. Will be super grateful for any advices on it

p.s.: please don’t advise to downgrade the node.js version

How do i convert an array of objects into 1 object in typescript

I have an array of objects like this:

myArray = [
    {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'},
    {itemThreeKey: 'itemThreeValue'}
];

I wish to turn it to a single object like this:

myObject = {
    itemOneKey: 'itemOneValue',
    itemTwoKey: 'itemTwoValue',
    itemThreeKey: 'itemThreeValue'
}

in TypeScript. Anyone have a clue how I can go about to achieve this?

loadAsync in JSZip is not waiting to get completed

I am using JSZip library on browser UI and having a “content” which I am passing as body for creating a zip.

var contentDiff: async function(content){
      zip = await JSZip.loadAsync(content, {base64: true});
      return zip.files;
},//other functions below this

Now, I am new but this “zip.files” comes as undefined in a later method call, even after calling await.
Kindly suggest what is missing in this js.

I tried different variations of async await and promises, but all in vain.

How to make slot conditionally rendered?

<template>
    <div class="carousel">
        {{ index}}
                <slot></slot>
         <button @click="next">Next</button>
    </div>

</template>
<script setup>
import { useSlots, onMounted, ref, onUpdated, provide} from 'vue';

const slots = useSlots()
const index = ref(0)
function next(){
    index.value = index.value + 1 == slots.default().length ? 0 : index.value + 1;
}
onUpdated(() => {
  const currentSlide = ref(slots.default()[index.value])
})
</script>

I’m creating my own carousel. I have const currentslide that equals the first object in my array by default.

I have to figure out how to provide and inject this const to my slot “Slide” and then make it conditionally rendered. It means that the current slide that is shown in my carousel is 0 by default but I can change by clicking on the button next

<template>
    <div class="slide">

        <slot/>
    </div>
    
</template>
<script>

</script>

Display JSON Data by Category. Not all categories are visible

There are separate categories on my page. But it is not possible to exclude all categories.

index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Display JSON Data by Category</title>
</head>
<body>
  <label for="category-select">Filter by Category:</label>
  <select id="category-select">
    <option value="all">All</option>
    <option value="fruits">Fruits</option>
    <option value="vegetables">Vegetables</option>
    <option value="dairy">Dairy</option>
  </select>

  <div id="category-container"></div>

  <script src="app.js"></script>
</body>
</html>

app.js:

// Wait for the DOM to finish loading
document.addEventListener("DOMContentLoaded", function() {

  // Get references to the category select element and category container element
  var categorySelect = document.getElementById("category-select");
  var categoryContainer = document.getElementById("category-container");

  // Attach an event listener to the category select element
  categorySelect.addEventListener("change", function() {
    // Get the selected category
    var category = categorySelect.value;

    // Send an AJAX request to the server to get the data for the selected category
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        // Parse the JSON response
        var data = JSON.parse(xhr.responseText);

        // Filter the data by the selected category
        if (category) {
          data = data.filter(function(item) {
            return item.category == category;
          });
        }

        // Build the HTML to display the filtered data
        var html = "";
        data.forEach(function(item) {
          html += "<h2>" + item.name + "</h2>";
          html += "<p>" + item.description + "</p>";
        });

        // Update the category container with the HTML
        categoryContainer.innerHTML = html;
      }
    };
    xhr.open("GET", "app.php?category=" + encodeURIComponent(category), true);
    xhr.send();
  });

});

data.json:

[
  {
    "name": "Apple",
    "description": "A sweet fruit that is good for you.",
    "category": "fruits"
  },
  {
    "name": "Broccoli",
    "description": "A nutritious vegetable that is high in fiber.",
    "category": "vegetables"
  },
  {
    "name": "Milk",
    "description": "A dairy product that is a good source of calcium.",
    "category": "dairy"
  },
  {
    "name": "Carrot",
    "description": "A root vegetable that is crunchy and delicious.",
    "category": "vegetables"
  },
  {
    "name": "Banana",
    "description": "A delicious fruit that is high in potassium.",
    "category": "fruits"
  }
]

app.php:

<?php

// Read the contents of the data.json file
$data = file_get_contents('data.json');

// Decode the JSON data into an array of items
$items = json_decode($data, true);
$itm = json_encode($items);

// Check if the category parameter is set and filter the items by category
if (isset($_GET['category'])) {
    if($_GET['category']!=="all"){
    $category = $_GET['category'];
    $items = array_filter($items, function($item) use ($category) {
        return $item['category'] == $category;
    });
    }
}

// Set the content type header to indicate that we are sending JSON data
header('Content-Type: application/json');

// Send the filtered items as JSON data
if($_GET['category']!=="all"){
echo json_encode(array_values($items));
}else{
    echo $itm;
}

This code reads the contents of the data.json file, decodes the JSON data into an array of items, filters the array by category if the category parameter is set, and then sends the filtered items as JSON data to the web page.

If I select a specific category:
working

If I select the “All” category:
not working

I want to see all categories.

Where did I go wrong? Thank you!

How does this link work that uses <a with no href and id instead?

I am trying to understand the way the links on a page are working because I like the design.

This is the live page:

https://www.infohio.org/resources/g68

This is how the links are set up in the source code:

<a  style='color: #202020' class='resourcelink'  id="resourcelinktitle61570">
  <div class='zoo-teaser-title uk-margin-small'> Book Nook </div>
  <div class='zoo-teaser-desc uk-margin-small'> Explore, create, and share video book trailers. Includes recommended web tools for creating book trailers, lesson plans, and other teacher resources. Lexile reading levels included.</div>
</a>

I’ve never seen a link like this. Can someone explain how it’s working?

I tried recreating the code on a page on my local machine and can’t get the links to work.

Why product array is not displaying all elements while using state from useSelector?

Here product is not showing all elements from the array. This is Home Code.
I made a schema of products now I made a reducer.js file in which I assigned products=> array now this fetch details from productAction.js everything works correctly and shows product[0] as a result but after applying map function in home.js product[1]-product[10] does not show up on screen.

import React, { Fragment, useEffect } from "react";
import { CgMouse } from "react-icons/cg";
import "./Home.css";
import ProductCard from "./ProductCard.js";
import MetaData from "../layout/MetaData";
import { clearErrors, getProduct } from "../../actions/productAction";
import { useSelector, useDispatch } from "react-redux";
import Loader from "../layout/Loader/Loader";
import { useAlert } from "react-alert";

const Home = () => {
  const alert = useAlert();
  const dispatch = useDispatch();
  const { loading, error, products } = useSelector((state) => state.products);

  useEffect(() => {
    if (error) {
      alert.error(error);
      dispatch(clearErrors());
    }
    dispatch(getProduct());
  }, [dispatch, error, alert]);

  return (
    <Fragment>
      {loading ? (
        <Loader />
      ) : (
        <Fragment>
          <MetaData title="eDavaa" />

          <div className="banner">
            <p> </p>
            <h1> </h1>

            <a href="#container">
              <button>
                Scroll <CgMouse />
              </button>
            </a>
          </div>

          <h2 className="homeHeading">Featured Products</h2>

          <div className="container" id="container">
            {products &&
              products.map((product) => (
                <ProductCard key={product._id} product={product} />
              ))}
          </div>
        </Fragment>
      )}
    </Fragment>
  );
};

export default Home;

Here is Product Reducer Code

export const productsReducer = (state = { products: [] }, action) => {
    switch (action.type) {
        case ALL_PRODUCT_REQUEST:
        case ADMIN_PRODUCT_REQUEST:
            return {
                loading: true,
                products: [],
            };
        case ALL_PRODUCT_SUCCESS:
            return {
                loading: false,
                products: action.payload.products,
                productsCount: action.payload.productsCount,
                resultPerPage: action.payload.resultPerPage,
                filteredProductsCount: action.payload.filteredProductsCount,
            };

        case ADMIN_PRODUCT_SUCCESS:
            return {
                loading: false,
                products: action.payload,
            };
        case ALL_PRODUCT_FAIL:
        case ADMIN_PRODUCT_FAIL:
            return {
                loading: false,
                error: action.payload,
            };

        case CLEAR_ERRORS:
            return {
                ...state,
                error: null,
            };
        default:
            return state;
    }
};

and Here is backend code ->

exports.getAllProducts = catchAsyncErrors(async (req, res) => {

    const resultPerPage = 8;
    const productsCount = await Product.findById(req.params.id);

    const apiFeature = new ApiFeatures(Product.find(), req.query).search().filter().pagination(resultPerPage);
    const products = await apiFeature.query;
    res.status(200).json({
        success: true,
        products,
        productsCount
    });
})

Here is product action code


// Get All Products
export const getProduct =
  (keyword = "", currentPage = 1, price = [0, 25000], category, ratings = 0) =>
  async (dispatch) => {
    try {
      dispatch({ type: ALL_PRODUCT_REQUEST });

      let link = `/api/v1/products?keyword=${keyword}&page=${currentPage}&price[gte]=${price[0]}&price[lte]=${price[1]}&ratings[gte]=${ratings}`;

      if (category) {
        link = `/api/v1/products?keyword=${keyword}&page=${currentPage}&price[gte]=${price[0]}&price[lte]=${price[1]}&category=${category}&ratings[gte]=${ratings}`;
      }

      const { data } = await axios.get(link);

      dispatch({
        type: ALL_PRODUCT_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: ALL_PRODUCT_FAIL,
        payload: error.response.data.message,
      });
    }
  };

Product Showing only one element that is product[0]? What should I Do.

I tried everything. But still no solution.

Three.js create n meshes to form a smooth 90 degree donut

I am trying to find an algorithm to have the following generated in Three.js.
Expected outcome (Pardon my drawing skills)
The amount of meshes to form the 90 degree donut, the thickness and the padding between them should be variable.

I know that you can create something like that with the TorusGeometry setting the radial segments to 2 and reducing the arc along the lines of:

const geometry = new THREE.TorusGeometry( 10, 3, 2, 100 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const torus = new THREE.Mesh( geometry, material );
scene.add( torus );

But this does not work because as seen in my expected outcome, I need seperate meshes. So I researched further and encountered the ShapeGeometry. I think the way to go is with ShapeGeometry.

const generateArc = (padding, thickness, count) => {
     const arcShape = new THREE.Shape()
        .moveTo( 50, 10 )
        .absarc( 10, 10, 40, 0, Math.PI * 2, false );
}

But I can’t figure out how to do the correct math to generate these seperate mesh arcs around.
Is my approach with ShapeGeometry the right one? and if so how do I generate the right meshes with the Shape geometries.

Troubleshooting “Non-Error promise rejection captured with value: Object Not Found Matching Id” in Sentry, from MERN App

enter image description here

This is an issue we’ve had for a while now, although this error has recently been appearing much more frequently for us in Sentry. Clicking into the issue does not give us much more info:

enter image description here

Like any painful error, we are having difficulty recreating the issue on our end – going to these website URLs does not cause this issue locally for me (although, I am on Mac, not Windows). A few related questions we have:

  • is this something we can safely ignore in Sentry?
  • if safe to ignore, is it better to ignore in the Sentry website in the Browser by clicking the ignore button, or by adding ignoreErrors into our Sentry.init() with

We initialize Sentry in our React App with this snippet in our index.js file:

Sentry.init({
    dsn: config.dsn,
    integrations: [
        new Integrations.BrowserTracing()
    ],
    tracesSampleRate: 1.0
});

and we initialize in our Node App in it’s index.js file:

const sentryDsn = env === 'development' ? null : config.SENTRY_DSN;
Sentry.init({ dsn: sentryDsn, tracesSampleRate: 1.0 });

I show both initializations as I am not sure if this is an error coming from our React app or our Node App, although I think it’s from our React App. Also, from this article, it seems like we could ignore these errors directly from our app with the following added to Sentry.init({}):

ignoreErrors:[
   "Non-Error exception captured",
   "Non-Error promise rejection captured"
]

We also found this related github issue, although it doesn’t seem like there are any great conclusions in here as well. Any recommendations as to what our best course of action is here, and how we could potentially further troubleshoot this, would be super helpful! Thanks!

Google Tag Manager trigger based on changed variable in datalayer

I have a variable watchedVariable that can either be “ABC” or “DEF” and a tag that should fire every time the value of watchedVariable changes from “ABC” to “DEF” or vice versa.

I tried to write a javascript that pushes e.g. "event" : "watchedVariable changed" based on an older entry I found, but I can’t apply it to my use case (my js skills are pretty basic).

I adjusted the name of {{watchedVariable}} and the dataLayer.push command at the end. Is there more to adjust?

Would be super thankful for any help on this!

<script>
var someEventIsTriggered = function(e) {
    var target = $('input#watched');
    var lastEvent = dataLayer
                        .filter(function (e) { return e.event === 'gtm.customEvent'; })
                        .pop();
    var lastValue = lastEvent instanceof Object 
                        ? lastEvent[{{watchedVariable}}] 
                        : false;

    // Trigger a generic "gtm.click" event on every click
    dataLayer.push({
        "event": "gtm.customEvent",
        {{watchedVariable}}: target.val()
    });

    if (lastValue !== target.val()) {
        dataLayer.push({
        "event": "watchedVariable changed"
    });
    }

};
</script>```

Is there a best practise way to get named anchor links rather than using IDs?

Bit of a novice, but I’ve got some legacy code to generate a Table of Contents based on adding an incremented ID to each of the H2 elements on a page.

As these can change order, I’d be hesitant to link to blah.com/help/article-1#4.

In the scenario that the anchor link’s H2 text is “Creating a post”, what can I do to this code to get the ID to be creating-a-post, resulting in the dynamic link being blah.com/help/article-1#creating-a-post?

const $headers = $(".article-body > h2, h3");

$headers.each((i, el) => {
  const $el = $(el);

  // skip it if it already has a link inside
  if ($el.has("a").length != 0) {
    return;
  }

  let idToLink = "";

  // skip it if it already has an id
  if ($el.attr("id") === undefined) {
    // give it ID to match
    idToLink = "" + i;
    $el.attr("id", idToLink);
  } else {
    // make sure the ID matches
    idToLink = $el.attr("id");
  }
});

$(document).ready(function () {
            setTimeout(() => {
                // Get ToC div
                if(document.querySelectorAll('.article-body > h2').length > 0) {
                
                toc = document.getElementById("ToC"); 
              //Add a header
                tocHeader = document.createElement("h2");
                tocHeader.innerText = "In this article";
                toc.appendChild(tocHeader); 
              // Get the h2 tags — ToC entries

                tocList = document.createElement("ul");
                // tocContainer.appendChild(tocList);
                // document.getElementById("div").appendChild(tocList);

                $('.article-body > h2').each(function () {
                    tocListItem = document.createElement("li");
                    // a link for the h2
                    tocEntry = document.createElement("a");
                    tocEntry.setAttribute("href", "#" + $(this).attr('id'));
                    tocEntry.innerText = $(this).text();
                    tocListItem.appendChild(tocEntry);
                    tocList.appendChild(tocListItem);
                });
                toc.appendChild(tocList);

                }
            });
        });

Is this even the best route?