React: Clean up function can’t catch error properly?

I am trying to abort a fetch in a useEffect clean up function but it seems that, even if the error is catch in the code and logging the ‘Error catching’, there is still a default js error triggering somewhere …

Simple code to test:

useEffect(() => {
    const url = "https://swapi.dev/api/films/1/";
    const controller = new AbortController()
    fetch(
        url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            signal: controller.signal,
        }
    ).then(function(response) {
        response.json().then(function(data) {
            console.log('Success', data)
        }).catch(function(error) {
            console.log('Json error', url)
        })
    }).catch(function(error) {
        console.log('Error catching', url)
    })

    return () => {
        console.log("Cleanup")
        controller.abort()
    }
}, [])

Output:
output screen

I tried to replace then/catch by try/catch but I think I am using it correctly and anyways it didn’t change anything.

I expect the error to be catch in the function AND not triggering the default behavior for js error (console.error).

Thanks for any solution, I already tested a lot of different things and I still can’t understand what is happening.

Uncaught Exception {“”errorType””:””Runtime.ImportModuleError””,””errorMessage””:””Error: Cannot find module ‘serverless’

i setup the nest js application using serverless and when im using sls offline it works fine but when i deployed it gives errors:

error logs:-
1712045182841,”2024-04-02T08:06:22.841Z undefined ERROR Uncaught Exception {“”errorType””:””Runtime.ImportModuleError””,””errorMessage””:””Error: Cannot find module ‘serverless’
Require stack:

  • /var/runtime/index.mjs””,””stack””:[“”Runtime.ImportModuleError: Error: Cannot find module ‘serverless'””,””Require stack:””,””- /var/runtime/index.mjs””,”” at _loadUserApp (file:///var/runtime/index.mjs:1087:17)””,”” at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)””,”” at async start (file:///var/runtime/index.mjs:1282:23)””,”” at async file:///var/runtime/index.mjs:1288:1″”]}

    1712045182896,”INIT_REPORT Init Duration: 163.55 ms Phase: invoke Status: error Error Type: Runtime.ExitError

sls offline works fine](https://i.stack.imgur.com/jkvtH.png)

but deployed code to aws lamda its not working..

Changing Next.js route with vanilla Javascript

I need to change the route of a Next.js application using vanilla Javascript. I want this code to work on Chrome Dev Tools so I cannot change the route dynamically with Next.js so I have to achieve this with plain Javascript.

I was able to do this on Vue.js applications like this:

window.history.pushState({}, '', '/directory');
window.dispatchEvent(new Event('popstate'));

Unfortunately popstates are not working on Next applications. I need a wayaround to that, I’m sure the code should resemble the Vue.js example, but I cannot figure that out.

Execution failed for task ‘:react-native-audio:compileDebugJavaWithJavac’. > Compilation failed; see the compiler error output for details

I am trying to run my react-native-app , it gives me this error , how can i solve this
error ?

FAILURE: Build failed with an exception.

  • Where:
    Build file ‘/home/ahmad/Desktop/New Folder/IOsReactNative-master/node_modules/react-native-audio/android/build.gradle’ line: 28

  • What went wrong:
    A problem occurred evaluating project ‘:react-native-audio’.

Could not find method compile() for arguments [directory ‘libs’] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

BUILD FAILED in 7s
info Run CLI with –verbose flag for more details.

I replaced method compile() by method implementation() , and after rerun the project it gives me this error :

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:react-native-audio:compileDebugJavaWithJavac’.

Compilation failed; see the compiler error output for details.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

BUILD FAILED in 4m 12s
error Failed to install the app.

to make data layer variable and Custom java script variable work the same in GTM

You need to write code for a javascript variable in GTM that will work similarly to a data layer variable. My current code doesn’t work in GSM, what’s wrong with it?

function() {    
  var res = null

  if (dataLayer[dataLayer.length - 1] == undefined) {
    res = 'undefined'
  } else {
      res = dataLayer[dataLayer.length - 1]['eventCategory']
  }
  return res
}

Task: to make data layer variable and Custom java script variable work the same in GTM

enter image description here

enter image description here

Return false does not break the each loop in cypress

This is the code snippet I have

cy.get('[data-testid="userRecords"]')
  .each((record) => {
    if (record.find('[data-testid="delete"]').is(":enabled")) 
    {
        cy.wrap(record).find('[data-testid="delete"]').click()
        if (someValue == 1) 
        {
            cy.get('[data-testid="test"]').should("be.visible");
        }
        else 
        {
            cy.get('[data-tstid="anotherTest"]').should("be.not.exist")
        }
        return false;
    }

The goal I am trying to achieve here is that if the outer if statement is entered, then I want to break the each loop.

Can someone guide me why I am not able to exit the each loop?

(0 , _react.createContext) is not a function on Nextjs using Material Tailwind

I’m working on a Nextjs(14) project with Ts and i’ve follow the instructions on the doc of MT here.
I faced this error while trying to add ThemeProvider of MT in my layout.tsx file

This is my layout.tsx below

import type { Metadata } from "next";
import { Urbanist } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "@material-tailwind/react";
const urbanist = Urbanist({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <ThemeProvider>
        <body className={urbanist.className}>{children}</body>
      </ThemeProvider>
    </html>
  );
}

```.

How to build and run next js app independently using node server

I am new to Next JS and React JS
I have a simple next js app, i want to build that application which can be done using command

npm run build

which creates a .next folder, now i want to copy that .next folder and run that as an separate application using node server or http server, can this be done ?

I used to work on angular earlier and we were able to do so, with dist folder created after the build

Javascript – Regex Comparison not working as expected

const columnDateIndex = [
  { path: "2023|Jan 2023" },
  { path: "2023|Feb 2023" },
  { path: "2023|Mar 2023" },
  { path: "2023|Apr 2023" },
  { path: "2023|May 2023" },
  { path: "2023|Jun 2023" },
  { path: "2023|Jul 2023" },
  { path: "2023|Aug 2023" },
  { path: "2023|Sep 2023" },
  { path: "2023|Oct 2023" },
  { path: "2023|Nov 2023" },
  { path: "2023|Dec 2023" },
  { path: "2024|Jan 2024" },
  { path: "2024|Feb 2024" },
  { path: "2024|Mar 2024" },
  { path: "2024|Apr 2024" },
  { path: "2024|May 2024" },
  { path: "2024|Jun 2024" },
  { path: "2024|Jul 2024" },
  { path: "2024|Aug 2024" },
  { path: "2024|Sep 2024" },
  { path: "2024|Oct 2024" },
  { path: "2024|Nov 2024" },
  { path: "2024|Dec 2024" },
];

const columnPath = "Williams|Bonus|2024|Feb 2024";

const result = columnDateIndex.find((column) => {
  const re = new RegExp(`${column.path}$`);
  return re.test(columnPath);
});

console.log(result);

Output:
{ path: ‘2024|Jan 2024’ }

Expected Output:
{ path: “2024|Feb 2024” }

I want to get the exact end match.

ASP.Net Using Data in Array to Populate HTML Map Areas Tooltips and Data Captions

I have an HTML page which reads the data from a data array in an ASP.Net controller. The data is used to create map areas which will then show the data as a tooltip and also fill caption boxes. I have successfully created the areas using a modified version of the code on the ImageMapster Beatles Menu page:

<img id="mainmap" src="/images/1641Map1.jpg" style="width:879px;  height:1557px" usemap="#main-map">
 @foreach (var item in Model.Areas)
{
<area shape="rect" data-full="@item.Name" data-name="@item.Name,all" coords="@item.Left,@item.Top,@item.Right,@item.Bottom" href="#"  />
}
<div style="width:390px; height: 120px; font-size: 12px; ">
<div id="1641-caption" style="clear:both;border: 1px solid black; width: 400px; padding: 6px; display:none;">
    <div id="1641-caption-header" style="font-style: italic; font-weight: bold; margin-bottom: 12px;"></div>
    <div id="1641-caption-text"></div>
</div>

The following Javascript is where I am having trouble. This is fixed and does not read from the data array provided:

<script>
$(document).ready(function () {
    alert("ready")
});
var inArea,
    map = $('#mainmap'),

captions = {
        area1: ["Area 1 Caption", "Area 1 Text"],
        area2: ["Area 2 Caption", "Area 2 Text"],
        area3: ["Area 3 Caption", "Area 3 Text"],
        area4: ["Area 4 Caption", "Area 4 Text"],
    },
//When mouse moves over individual areas:
single_opts = {
    fillColor: '000000',
    fillOpacity: 0.1,
    stroke: true,
    strokeColor: 'ff0000',
    strokeWidth: 2
},
    //When mouse moves over image:
    all_opts = {
        // fillColor: 'ffffff',
        fillColor: '000000',
        fillOpacity: 0,
        stroke: true,
        strokeWidth: 1,
        strokeColor: '000000'
    },
    initial_opts = {
        mapKey: 'data-name',
        isSelectable: false,
        singleSelect: true,
        fill: true,
        mapkey: 'id',
        fillOpacity: 0.3,
        fillColor: 'ff0000',
        clickNavigate: true,
        showToolTip: true,

        onMouseover: function (data) {
            inArea = true;
            $('#1641-caption-header').text(captions[data.key][0]);
            $('#1641-caption-text').text(captions[data.key][1]);
            $('#1641-caption').show();
        },
        onMouseout: function (data) {
            inArea = false;
            $('#1641-caption').hide();
        },
        areas: [
            {
                key: "area1",
                toolTip: "Area 1 Caption"
            },
            {
                key: "area2",
                toolTip: "Area 2 Caption"
            },
            {
                key: "area3",
                toolTip: "Area 3 Caption"
            },
            {
                key: "area4",
                toolTip: "Area 4 Caption"
            }
        ]
    };
opts = $.extend({}, all_opts, initial_opts, single_opts);
map.mapster('unbind')
    .mapster(opts)
    .bind('mouseover', function () {
        if (!inArea) {
            // Registers mouse move over image
            map.mapster('set_options', all_opts)
                .mapster('set', true, 'all')
                .mapster('set_options', single_opts);
        }
    }).bind('mouseout', function () {
        if (!inArea) {
            map.mapster('set', false, 'all');
        }
    });

The array being read contains the Name (the name of the area), Left, Top, Right, Bottom, plus the actual data that I would like to display. I found the following code to copy the data into a Javascript array:

var myArray = [];

@foreach (var d in Model.data)
{
    @:myArray.push("@d");
}

Changing the Model.data to my own array Model.Areas but my knowledge of Javascript is limited and I couldn’t work out how to take this array and apply it to the areas dynamically.

Integrate Shaka player into web application via webpack config

I have an existing typescript application with Shaka 3.2.1 integration. Now I am facing some issue with subtitle, so I want to use the uncompiled version of shaka and edit the library.

From Shaka documentation we can use the uncompiled version of shaka by using the following scripts in HTML.

    <script src="node_modules/google-closure-library/closure/goog/base.js"></script>
    <!-- Deps file: -->
    <script src="dist/deps.js"></script>
    <!-- Shaka Player uncompiled library: -->
    <script src="shaka-player.uncompiled.js"></script> 

How can we integrate the uncompiled version of Shaka via Webpack config?

Any help will be greatly appreciated. Thanks in Advance

Trouble fitting vertical image in my carousel of horizontal images (React.js)

I’m currently writing a photo portfolio web-app using React and Tailwind. I’ve managed to modify a carousel I’ve found according to my needs.

Everything works as intended right until an image of a different orientation is introduced – then it falls apart.

At first, the height was fitting with the rest of the images but the carousel (based on css transform) was making a stop between two images (half of each image visible on each side).
pic:(https://i.stack.imgur.com/ZIghF.png)

I’ve managed to fix this by setting the img min-width to 100%. That, however, made the vertical image much bigger than the others. Set in few other parameters and now the vertical image, while not that big, is getting either squashed or cropped (depending on whether margin: auto is on).

One solution that got the carousel to a sort-of competent state is giving the images a large left and right padding (like 10em) – but then every horizontal images gets too tiny and it’s at odds with the design choices I’m supposed to follow.

Imaginary solutions (that didn’t work):

  • I’ve thought about introducing some auto-padding for the img elements which would fill the empty space (if there is any) to fit the container. I’ve tried for an hour and gave up with it.

  • I’ve also thought about giving the vertical images a class that would style them with padding and a negative margin (I’ve found parameters that made it look acceptable using browser dev tools) but I’ve had trouble with doing it programmatically. I gave up with it after another hour as I realized that even if I got it to somehow work, it would be a pretty janky solution anyway.

Here is the demo build of the page in question:

https://szczek.github.io/ola-portfolio/#/projekty/1

Below is my current code:

import { useState } from "react";

const slides = ['https://images.unsplash.com/photo-1707343848610-16f9afe1ae23?q=80&w=2670&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', 'https://plus.unsplash.com/premium_photo-1687975124217-797c741d2a40?q=80&w=2787&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', 'https://images.unsplash.com/photo-1711971782079-62a788d72e73?q=80&w=2678&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', 'https://64.media.tumblr.com/139152f8a52760bbc53b9be439194eb4/tumblr_pw4pecjMWA1sfa5q9o1_500.jpg', 'https://images.unsplash.com/photo-1711968267709-12c4f6a8ddc3?q=80&w=2670&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D']

export default function ViewProject () {

    let [current, setCurrent] = useState(0);

    let previousSlide = () => {
      if (current === 0) setCurrent(slides.length - 1);
      else setCurrent(current - 1);
    };
  
    let nextSlide = () => {
      if (current === slides.length - 1) setCurrent(0);
      else setCurrent(current + 1);
    };


    return(
        <div className="flex my-[25%] sm:my-[10%] lg:my-[5%]" >
            <div className='carousel-wrapper px-2 mx-auto flex'>      
                <button onClick={previousSlide}>
                        &lt;
                </button>

                <div className="overflow-hidden relative max-w-full md:max-w-screen-md mx-8">

                    <div
                        className={`flex transition ease-out duration-40 max-h-[750px]`}
                        style={{
                        transform: `translateX(-${current * 100}%)`,
                        }}
                    >
                        {slides.map((s) => {
                        return <img src={s} className={"carousel-image block relative mx-auto top-[50%]"} />;
                        })}
                    </div>
                    <div className="absolute bottom-0 py-4 flex justify-center gap-3 w-full">
                        {slides.map((i: any) => {
                        return (
                            <div
                            onClick={() => {
                                setCurrent(i);
                            }}
                            key={"circle" + i}
                            className={`rounded-full w-5 h-5 cursor-pointer  ${
                                i == current ? "bg-white" : "bg-gray-500"
                            }`}
                            >
                            </div>
                            );
                            })}
                    </div>
                </div>
                <button onClick={nextSlide}>&gt;</button>
            </div>
        </div>
    )
}

I’ve also, temporarily, been working on a css sheet just to make the experimentation quicker; here is the styling for the carousel.

.carousel-image{
    margin: auto;
    padding: auto;
    position: absolute;
    min-width: 100%;
    top: 50%;
    transform: translateY(-50%), translateX(-50%);
}

I’ve been stuck with this for some time already so any help will be appreciated. Thanks.

Odin project loops and arrays foundation assignment [closed]

Write a function with 2 arguments which returns repeated results, something like this :

function repeatString(string, times) {
    let result = "BY";  // Initialize the result variable with the value "BY"

    for (let i = 0; i < times; i++) {
        result += string;  // Concatenate the input string to the result string
    }
    
    return result;  // Return the accumulated repeated string
}

Example usage:

let repeated = repeatString("Hello", 3);
console.log(repeated); // Output: "BYHelloHelloHello"

So, my question is why is that the BY value is not repeated and only the Concatenated string is repeated, when both are included inside the loop?