How to check if the directory is not empty and contains and image in React using custom hooks

I’m working on a custom hook for checking directories of specific markets and I want to check if there’s an existing image inside. If there is then import the image if not then return a default. This is my code so far without returning the default image.

import { useState, useEffect } from 'react';
import { brand, country } from '../resources';
    
const useImgFromDir = (fileName: string) => {
  const [image, setImage] = useState<string>('');

  useEffect(() => {
    const importFile = async () => {
      try {
        const image = await import(`../dir/images/${brand}/${country}/${fileName}.png`);
        // I'm not sure how to use the condition here
        // For now the code is working on not empty directory
        setImage(image.default);
      } catch {
        setImage('');
      }
    };

    importFile();
  }, [brand, country, fileName]);

  return image ?? '';
};

export default useImgFromDir;

trying to create chrome extension but manifest.json not working

so basically, I have build a small game using javascript and trying to create a chrome extension. This is my first time not sure what I am doing wrong in the manifest.json.

I have got multiple folder, 3 folders for images. Not sure what is wrong here.

{
  "manifest_version": 3,
  "name": "DICE CAR RACE",
  "version": "1.0",
  "description": "CLICK THE DICE AND MOVE THE CAR",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "index.html"
  },
  "permissions": [
    "activeTab"
  ],
  "web_accessible_resources": [{
    "resources" : ["diceImg/dice1.jpeg",
    "diceImg/dice2.jpeg",
    "diceImg/dice3.jpeg",
    "diceImg/dice4.jpeg",
    "diceImg/dice5.jpeg",
    "diceImg/dice6.jpeg",
    "cars/car1.jpeg",
    "cars/car2.jpeg",
    "cars/car3.jpeg",
    "cars/car4.jpeg",
    "cars/car5.jpeg",
    "cars/car6.jpeg",
    "racecourse/racetrack.jpeg"],
    "matches": ["<all_urls>"]}
]
}

Is it possible to take code from a website and turn it into a bookmarklet without having it attached to the link?

The title probably does a horrible job at explaining this, but I didn’t know how to word it any better. If someone wants to edit that go ahead.

On to the point, I want to take code from a website my friends made and make it a bookmarklet that turns your screen into that website without actually bringing you to the website, if that makes sense. (they know I want to do this and are ok with it)

I found this code that replaces whatever is currently on your screen:
Code

But I don’t know how to or if I can even make it show a entire website. Another problem with this is the website uses multiple pages and multiple coding languages (HTML, CSS, JS, and pages to store the code I think) and bookmarklets were made for Javascript specifically and one page I think, unless i’m wrong.

Sorry if this appears to be a blatantly obvious or dumb question, I am very new to Javascript and this is probably a big thing to even try to do for someone who just started but I feel like doing it and unless it’s impossible I will do it lol.

When you pass a variable to a constructor, will updating that variable update objects?

In the following code, I create a constructor named Foo, then create a new object called zzz that uses that constructor and is called with reference to another variable.

function Foo(bar) {
    this.a = bar;
}
const bar = [10, 10, 10];
const zzz = new Foo(bar);
console.log(zzz.a[0]);
bar[0] = 0;
console.log(zzz.a[0]);

This prints out 10, 0. I would expect that zzz.a is initialized as a copy of bar, but I found that changing bar will change the zzz object as well. Can someone explain why this happens?

Normalize Special Letter Char from Various Foreigner Languages

Forgive my ignorance for not knowing the technical term for foreigner languages that use characters as

  • ø i.e. Helsingør
  • Ł i.e Łeczna
  • ı i.e Altınordu
  • ł i.e. Głogow

how could I normalize those with Javascript (write a regex), while also making case insentive?

const strArr = ['Helsingør', 'Łeczna', 'Altınordu', 'Głogow']

With the code below, I was able to replace latin based characters (é, ñ, ô, etc) but not the above ones.

strArr.map(string => string.normalize('NFD')
    .replaceAll(/[u0300-u036f,"'"]/g, ''))

Using leaflet in native web component

I’m trying to use leaflet inside of a web component. Here’s my code.

I’ve copy pasted the standard example on leaflet website, but given it a HTMLElement rather than id string.

class InfoWithMap extends HTMLElement {
  constructor(){
    super().attachShadow({mode: 'open'});
  }
  connectedCallback(){
    let container = `
    <style>
      #map {
        height: 500px;
        width: 100%;
      }
    </style>
    <div id='container'>
      <div>Name: Someone</div>
      <div>Location: Some place</div>
      <div id='map'></div>
    </div>`
    this.shadowRoot.innerHTML = container;
    
    let mapDiv = this.shadowRoot.getElementById('map');
    var map = L.map(mapDiv).setView([51.505, -0.09], 19);

    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);
  }
}

window.customElements.define('info-with-map', InfoWithMap);


let m = document.createElement('info-with-map');
document.getElementById('main').append(m);
#main {
  width: 50%;
}
<!-- https://leafletjs.com/examples/quick-start/ -->

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
     integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
     crossorigin=""/>

 <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
     integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
     crossorigin=""></script>

<div id="main"> 
</div>

However, as you can see the map is not being shown properly.

Any idea what is wrong with the setup?

I need help understanding what a line in a JavaScript algorithm does

Im working on breaking down an algorithm called Top K Frequent Elements below i have the link to the problem and the solution. I cant understand what the 4th line is doing specifically on the right side of the = sign, could someone explain to me what it is that im assigning to the map[elements], it seems to perhaps be short hand for some type of if conditional because of the || statement but that is my best guess. If im missing any information or if my question is not clear please let me know and I will update the question as soon as I can
https://leetcode.com/problems/top-k-frequent-elements/description/

var topKFrequent = (nums, k) => {
let map = {}
for(let element of nums){
    map[element] = (map[element] || 0) + 1
}
return Object.entries(map).sort((a,b) => b[1] -a[1]).map(val=>Number(val[0])).slice(0,k);
}

How to passing data from middleware to components/api in Next Js 13?

i just trying Next Js 13 middleware feature. But i confuse how to passing data from middleware to components/page/api.

For example i try to pass payload or who user is currently loggin.

Normally without middleware feature, i just make middleware file and if jwt verify true, i will send/pass payload data to my components/api

import {example} from 'middleware/example'

const payload = await example(req, res)

But if i using Next Js 13 feature and i read the docs, i just find how to send response like

return new NextResponse(
  JSON.stringify({
    success: false,
    message: 'authentication failed'
  }),
  { status: 401, headers: { 'content-type': 'application/json' } }
)

if i use that, it will return json data, and not continue the middleware chain, if i use

return NextResponse.next()

it will continue the middleware chain, but how do i passing my payload data to components/page/api?.
im trying like this

return NextResponse.next({tes: "tes"})

but i can’t find how to get that data from components/api.

This is my middleware code

if (request.nextUrl.pathname.startsWith('/api/posts')) {
        const requestHeaders = new Headers(request.headers)
        const authorization = requestHeaders.get('authorization')

        if (!authorization) {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        const authSplit = authorization.split(' ')
        const [authType, authToken] = [
            authSplit[0],
            authSplit[1]
        ]

        if (authType !== 'Bearer') {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        const payload = await verify(authToken)

        if (!payload) {
            return new NextResponse(
                JSON.stringify({
                    success: false,
                    message: 'authentication failed'
                }),
                { status: 401, headers: { 'content-type': 'application/json' } }
            )
        }

        return NextResponse.next()
    }

Can’t play sound from an array using Javascript

I’m trying to create a Drum Kit website. I use array as a placeholder to all the sound files, and use loop to call the play() function.
When I try to load, the debug consol said: “Uncaught DOMException DOMException: Failed to load because no supported source was found.”

The problem is that if I replace “audio.src = playlist[i];” by “audio.src = playlist[1];”, the website can locate the source of the file & play the selected sound. But if I replace [1] by [i], the website can’t locate the source file. So why is it?

Do you know why Javascript behaves this way? I can find another way to get the website to work but this thing has been tickling in my mind for a while.

Below is my Javascript codes:

var audio = new Audio();

var playlist = new Array("sounds/crash.mp3","sounds/kick-bass.mp3","sounds/snare.mp3","sounds/tom-1.mp3","sounds/tom-2.mp3","sounds/tom-3.mp3","sounds/tom-4.mp3");

var drum = document.querySelectorAll(".drum")

for (var i = 0; i < drum.length; i++) {
        drum[i].addEventListener("click", play);
        function play() {
            audio.src = playlist[i];
            audio.play();       
            }
    }

Failed to load module script: Expected a JavaScript module for a stencil application

I have a stencil Application where on build the files are moved to s3, i see in my cloud formation template while uploading the content type is set as application/javascript.

name": "stencil-base/build/stencil-base_esm",
  "sourceLocation": "./stencil-base/build/stencil-base.esm.js",
  "destinationLocation": "stencil-base/build/stencil-base.esm.js",
  "headers": {
    "cache-control": "no-cache, no-store, must-revalidate, max-age=0",
    "x-amz-meta-content-security-policy": {
      "template": "default-src 'self' {{CloudFrontProtocol}}://{{CloudFrontDomain}}",
      "templateType": "handlebars"
    },
    "content-type": "application/javascript; charset=utf-8"
  },
  "replacements": []

But when the code is pulled from s3 . I get error in the browser .

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.

I tired changing the extension to .mjs but nothing works. what is the missing piece here

Unable to assign value of original type in Array.reduce function

I’m creating a function which takes a boolean indicator object like:

const fruits = {
  apple: false,
  banana: false,
  orange: false,
  mango: false,
};

And an array like ['apple', 'orange']. It should return object similar in structure of input object
with properties in array turned true.

I’ve these typescript functions to achieve it


// Helper function to type Object.Keys
const objectKeysTyped = <Obj extends object>(obj: Obj) => {
  return Object.keys(obj) as (keyof Obj)[];
};

// Main function
const arrayToBoolIndicator = <Obj extends Record<string, boolean>>(
  boolFramework: Obj,
  arrayOfIncluded: (keyof Obj)[]
) => {
  return objectKeysTyped(boolFramework).reduce(
    (acc, cur) => {

      // TS Error next line: Type 'boolean' is not assignable to type 'Obj[keyof Obj]'.
      acc[cur] = arrayOfIncluded.includes(cur); 

      return acc;
    },
    { ...boolFramework }
  );
};

Typescript Playground link

Why am I getting the TS error while I’m assigning original type to object’s property?

Vue 3’s Provide / Inject using the Options API

I’ve been trying to follow the documentation for the API on the Vue 3 website which says to use app.provide('keyName',variable) inside your main.js file like so:

import App from './App.vue'
import { createApp } from 'vue'
import axios from 'axios'

const app = createApp(App)

app.provide('axios', axios)

app.use('Vue')
app.mount('#app')

Then inject and use it in your child component like so:

export default {
  inject: ['axios'],
  ...
  createUser (data) {
    return this.axios.post('/users', data)
  }
}

However doing so just gives me this error in my console:

Uncaught TypeError: Cannot read properties of undefined (reading 'post')

Is there anything I’m missing? I didn’t see any about an import unless you’re using the Composition API. Can provide / inject be called from within a .js file? I would expect so as long as its within a export default {} statement

Ive tried following the API to a “T” but it simply refuses to work for me. Also tried searching the web for solutions but everything I’ve found says what I’m doing should be working just fine.