How do I configure ESLint in VS Code for JS module script

I am using VS Code to work on a web page (using Leaflet). In my index.html I run the JS with:

<script type="module" src="js/main.js"></script>

I am using an ESLint plugin with VS Code and I want it to use strict JS rules for the linting, but though I have a “use strict”; at the top of main.js, it is only showing problems for non-strict issues.

I have an eslint.config.js file in the root of my project which looks like this:

import globals from "globals";
import pluginJs from "@eslint/js";

export default [
  {languageOptions: { globals: globals.browser }},
  pluginJs.configs.recommended,
];

What do I need to change to get ESLint to get it to respond to the “use strict”; command and what to do to make it the default so it’s not needed?

Thanks

WebNFC NDEFReader is not a constructor

 const handleRead = async() => {
    addLog("User clicked scan button");
    if ('NDEFReader' in window) {
      console.log('NDEFReader is supported');
    } else {
      console.log('NDEFReader is not supported');
    }
    try{
      const ndef = new window.NDEFReader();
      await ndef.scan();
      addLog("> Scan started");
      ndef.addEventListener("readingerror", () => {
        addLog("Argh! Cannot read data from the NFC tag. Try another one?");
      });
      ndef.addEventListener("reading", ({ message, serialNumber })=>{
        addLog(`> Serial Number: ${serialNumber}`);
        addLog(`> Records: (${message.records.length})`);
        const decoder = new TextDecoder();
        for(const record of message.records){
          if(record.recordType === "text")
            {
              const text = decoder.decode(record.data);
              addLog(`> Record text: ${text}`);
            }
        }
      }
        
      ); 
    }catch(error){
      addLog("Error: " + error)
    }
  }

when i try to change const ndef = new NDEFReader(); it will show the error: NDEFReader is not ‘NDEFReader’ is not defined no-undef. But if i keep this, in the logerr shows NDEFReader is not a constructor.

I had google it but solution didnt work. I have been add the https in to my react project

How to use js Fetch api get streaming audio chunks and play it?

here’s my code

I want to request the API to return the audio file by streaming, so as to achieve the effect of playing the audio file while requesting, but the returned int8 array cannot be played.

I think the problem is that the audio file is not decoded, but I don’t know how to decode it.

$("#start_stream").click(async function() {


const response = await fetch($("#apiurl").val(), {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json"
      },
    });

    const reader = response.body.getReader();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log("***********************done");
        $("#start_stream").prop("disabled", false);
        break;
      }
      console.log("--------------------value");
      console.log(value);

      var blob = new Blob([value], { type: 'audio/wav' });
    var url = window.URL.createObjectURL(blob)
    window.audio = new Audio();
    window.audio.src = url;
    window.audio.play();

      


    }




});

but get this error:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

the value is Uint8Array

Collaboration Diagrams (communication)

I have a big project on software engineering and I have to do some communication diagrams. The only thing I dont know how to draw the if then statements. Can someone help?

I searched on Youtube but the people explaining the diagrams only used simple examples without if then statements

How can Rust be slower than JavaScript?

I understand it’s a weird question to ask, but I am puzzled by this issue I have. I wrote two functions, one in JavaScript, one in Rust (with the intention of using it via WASM). I cannot share code, but, basically, it’s an implementation of the LTTB algorithm. Very basic approach, Float32Array in JS, [f32] and Vec with initial capacity set in Rust (so no push), no extra data structures, pretty straightforward math stuff. All in all a 1:1 code.

When I run the code against 20M points, I get around

120ms in JavaScript

but…

150ms in Rust

And it pretty much stays like that for any data, for example, on 70M points, Rust=520ms, JS=370ms

Note: I am measuring the exact duration of the LTTB algorithm inside Rust, not the overhead added by the Rust->JS data transfer.

Rust is compiled with

[profile.release]
codegen-units = 1
lto = "fat"
panic = "abort"
strip = "debuginfo"

I would have been ok with a tie, but the fact that JS is faster seems fishy to me.

Any insights would be greatly appreciated. Thanks!

Does Javascript share strings? [duplicate]

If I write

let x="hello"
let y="hello"

does Javascript make two references to the same string, or does it create two separate strings that happen to have the same content?

This first occurred to me when thinking about a micro-optimization. I had about 40 occurrences of an identical, 12 character string and I was wondering if that would take 12 bytes (plus whatever overhead) or 480. I quickly realized that was trivial either way so even if I modified the code to guarantee it’s the same chunk of memory, so what? But one could imagine cases where there could me a million copies of a 1000-character string, so it’s one of those things that would just be good to know.

It also led me to the broader question: How could I find out? In some languages I could dump the value of the reference and see if the two are the same, but I don’t know any way to do that in Javascript. And of course if I write “if (x==y)”, that’s going to be true because the contents are the same, so it would prove nothing.

Go Back Functionality in Remix and React

I wanted make a reusable back functionality for my app. I’m using Remix.
I wanted to achieve that if you click the “Back” button, it should redirect back to the previous page. However there is a fallBackRoute provided if there is no way to go back.
The problem right now is that, sometimes, when you click “Back”, it redirects you to the page outside of your website. How should we best fix that?

BackButton.tsx

import { useLocation, useNavigate } from "@remix-run/react";
import { ArrowLeft } from "lucide-react";
import { Button } from "~/components/ui/button";

export default function BackButton({ fallbackRoute}: { fallbackRoute: string }) {
    const navigate = useNavigate();
    const location = useLocation();

    return (
        <Button
            type="button"
            onClick={() => {
                if (location.key !== "default") {
                    navigate(-1);
                } else {
                    navigate(fallbackRoute);
                }
            }}
        >
            <ArrowLeft className="mr-2" /> Back
        </Button>
    );
}

Sample component

<BackButton fallbackRoute={`/orders`} />

Nextjs Clerk: The component is not configured correctly

I tried to solve the problems mentioned in the below error message but I failed. How do I solve this error and do “auth-callback with clerk”? – I have used Nextjs & Nextjs Actions, Clerk and Prisma.

Console Error Message
Clerk Error Image

Clerk Error Text:

Uncaught (in promise) Error:
Clerk: The component is not configured correctly. The most likely reasons for this error are:

  1. The “/olustur/onizleme” route is not a catch-all route.
    It is recommended to convert this route to a catch-all route, eg: “/olustur/onizleme/[[…rest]]/page.tsx”. Alternatively, you can update the component to use hash-based routing by setting the “routing” prop to “hash”.

  2. The component is mounted in a catch-all route, but all routes under “/olustur/onizleme” are protected by the middleware.
    To resolve this, ensure that the middleware does not protect the catch-all route or any of its children. If you are using the “createRouteMatcher” helper, consider adding “(.)” to the end of the route pattern, eg: “/olustur/onizleme(.)”. For more information, see: https://clerk.com/docs/references/nextjs/clerk-middleware#create-route-matcher


LoginModal.jsx

import { X } from "lucide-react"
import { SignIn } from "@clerk/nextjs"

export default function LoginModal({ isOpen, setIsOpen }) {
  return (
    <div className={`w-full h-full flex items-center justify-center fixed inset-0 z-[999] bg-[#000] bg-opacity-35 overflow-hidden ${isOpen ? 'flex' : 'hidden'}`}>
      <div className="relative">
        <SignIn />
        <X className="absolute top-4 z-10 right-4 w-4 h-4 cursor-pointer" onClick={() => setIsOpen(false)} />
      </div>
    </div>
  )
}

page.jsx (app/auth-callback/page.jsx)

'use client'

import { Loader2 } from "lucide-react"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { useQuery } from "@tanstack/react-query"
import { getAuthStatus } from "./_actions/actions"

export default function Page() {
  const router = useRouter()

  const [configId, setConfigId] = useState(null)

  useEffect(() => {
    const configurationId = localStorage.getItem('configurationId')

    if(configurationId) {
      setConfigId(configurationId)
    }
  }, [])

  const { data } = useQuery({
    queryKey: ['auth-callback'],
    queryFn: async() => await getAuthStatus(),
    retry: true,
    retryDelay: 500,
  })

  console.log(data)

  if(data?.success) {
    if(configId) {
      localStorage.removeItem('configurationId')
      router.push(`/olustur/onizleme?id=${configId}`)
    } else {
      router.push('/')
    }
  }

  return (
    <div className="w-full h-[94vh] flex items-center justify-center text-center">
      <div className="gap-0.5 flex flex-col items-center">
        <Loader2 className="w-8 h-8 animate-spin text-[#4e4e53]" />
        <h2 className="text-xl font-semibold">Giris yapildi..</h2>
        <p className="text-sm">Otomatik olarak yonledirileceksiniz..</p>
      </div>
    </div>
  )
}

actions.js app/auth-callback/_actions/actions.js

'use server'

import { db } from '@/app/db'
import { currentUser } from '@clerk/nextjs/server'

export const getAuthStatus = async() => {
  const user = await currentUser()
  console.log(user)

  try {
    if (!user?.id || !user.emailAddresses[0].emailAddress) {
      throw new Error('Gecersiz kullanici bilgileri!')
    }
  
    const existingUser = await db.user.findFirst({
      where: { id: user.id },
    })
  
    if (!existingUser) {
      await db.user.create({
        data: {
          id: user.id,
          email: user.emailAddresses[0].emailAddress,
        },
      })
    }
  
    return { success: true }
  } catch (error) {
    console.log('Error:', error)
    return { success: false }
  }
}

How do I make sure that the user name remains after the page has been updated?

I implemented verification by using passport-jwt in my back-end and then I made post request from client to server:

export const fetchVerifyUser = async (token) => {
  try {
    const response = await axios.post(
      "http://localhost:5000/verify",
      {},
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );
    console.log(response.data);
    return response.data;
  } catch (error) {
    throw error;
  }
};

When the user login in and the token appears I see all users data in network and in console.log() that I had written inside useEffect()

const Header = () => {
  const [anchorEl, setAnchorEl] = useState(null);
  const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
  const isMenuOpen = Boolean(anchorEl);
  const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
  const navigate = useNavigate();
  const token = localStorage.getItem("token");
  const dispatch = useDispatch();
  const profile = useSelector((state) => state.auth.user);

  useEffect(() => {
    if (token) {
      fetchVerifyUser(token);
      console.log(profile.user);
    }
  }, [token, profile.user]);

// ...other logic of the component
   return (
    <Box sx={{ flexGrow: 1 }}>
      <AppBar
        position="static"
        sx={{ backgroundColor: "rgb(31, 37, 61)" }}
        color="default"
      >
        <Toolbar>
          <IconButton
            size="large"
            edge="start"
            color="inherit"
            aria-label="open drawer"
            sx={{ mr: 2 }}
          >
            <MenuIcon sx={{ color: "white" }} />
          </IconButton>
          <Typography
            variant="h6"
            noWrap
            component="div"
            sx={{ display: { xs: "none", sm: "block" }, color: "white" }}
          >
            Cryptocurrency Dashboard
          </Typography>
          <Box sx={{ flexGrow: 1 }} />
          <Box
            sx={{
              display: {
                xs: "none",
                md: "flex",
                alignItems: "center",
              },
            }}
          >
            <IconButton size="large" sx={{ color: "white" }}>
              <Badge color="white">
                <DashboardIcon />
              </Badge>
            </IconButton>
            <IconButton size="large" sx={{ color: "white" }}>
              <Badge color="white">
                <InfoIcon />
              </Badge>
            </IconButton>
            {token && (
              <IconButton size="large" sx={{ color: "white" }}>
                <Badge color="white">
                  <Tooltip title={profile.user?.user}>
                    <PersonIcon />
                  </Tooltip>
                </Badge>
              </IconButton>
            )}
            {!token && <ButtonSignIn />}
            {token && <ButtonExit onClick={() => handleClickExit()} />}
          </Box>
          <Box sx={{ display: { xs: "flex", md: "none" }, color: "white" }}>
            <IconButton
              size="large"
              aria-label="show more"
              aria-controls={mobileMenuId}
              aria-haspopup="true"
              onClick={handleMobileMenuOpen}
              color="white"
            >
              <MoreIcon sx={{ color: "white" }} />
            </IconButton>
          </Box>
        </Toolbar>
      </AppBar>
      {renderMobileMenu}
      {renderMenu}
    </Box>
  );

Earlier, I had tried to render the user’s name inside a ToolTip, but when I refreshed the page, the user’s name inside the ToolTip disappeared. That’s why I decided to use Passport middleware. How can I connect my verification using passport-jwt and render the user’s name even after refreshing the page? Thanks.

Cant access deployed HTML/js files in Azure Web App

im very new to Azure so apologise if this is a stupid question.

Can I manually deploy a html and vanilla js project to Azure Web App? (Not Azure Static Web App)?

I have built my files and deployed to a Web App (App Service) that I created via VS Code Azure App Service plugin. On inspection of the directory via the SSH option in my Web App, I can see that all my files have been deployed to /home/site/wwwroot/ which is what I would expect. However when accessing my app URL I get presented with the default “Your web app is running and waiting for your content” page… I also cant access my html files via /index.html as I get “Cannot GET /index.html”.

My web app is set up for code deployment with a Node.js runtime, can I not deploy static html files to this app?

set background gradient over multiple html sections

I have multiple sections each with the background.

.grad-back{
background: rgb(0,92,109);
background: linear-gradient(180deg, rgba(0,92,109,1) 0%, rgba(1,12,14,1) 39%, rgba(1,9,10,1) 65%, rgba(0,93,110,1) 100%);
}
section {
height:200px;
}
<section class="grad-back">one</section>
<section class="grad-back">two</section>
<section class="grad-back">three</section>

What we would like is the same background over all sections so the gradiant starts on the top section and finishes on the bottom.

Problem with jump link have to much info when click on button in “form” class

<div class="input2">
  <form action="/browse/room" method="GET">
    <input type="text" name="search" class="search2" placeholder="Search..." value="<%= searchQuery || '' %>" />
    <button type="submit" style="background-color: #ffffff; border: none">
      <img class="search-icon2" alt="" src="/img/search.png" />
    </button>
  </form>
</div>

When I click on this button all content in any input will be sent to my URL, eg:

http://localhost:3000/browse/customer/?date=&search=&customer_id=1002&cccd_passport=&first_name=&last_name=&birthday=&gender=&email=&phone=&address=

I just want only the content in the search input sent to the URL.

I have tried to fix my JS file but there are not any lines of code that affect the jump link.

React questions for proper understanding of the topic

import { configureStore, createSlice } from '@reduxjs/toolkit';

const formSlice = createSlice({
  name: 'form',
  initialState: {
    name: '',
    dob: '',
  },
  reducers: {
    setName: (state, action) => {
      state.name = action.payload;
    },
    setDob: (state, action) => {
      state.dob = action.payload;
    },
  },
});

export const { setName, setDob } = formSlice.actions;

const store = configureStore({
  reducer: {
    form: formSlice.reducer,
  },
});

export default store;
type here
import React from 'react';
import { useSelector } from 'react-redux';
import ChildComponent from './ChildComponent';
import './ParentComponent.css';

const ParentComponent = () => {
  const name = useSelector((state) => state.form.name);
  const dob = useSelector((state) => state.form.dob);

  return (
    <div className="parent-container">
      <div className="user-info">
        {name && dob && (
          <h1>
            Welcome, {name}! Your date of birth is {dob}.
          </h1>
        )}
      </div>
      <div className="child-container">
        <ChildComponent />
      </div>
    </div>
  );
};

export default ParentComponent;

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { setName, setDob } from '../store';
import './ChildComponent.css';

const ChildComponent = () => {
  const dispatch = useDispatch();
  const [name, setNameInput] = useState('');
  const [dob, setDobInput] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch(setName(name));
    dispatch(setDob(dob));
  };

  return (
    <div className="child-form">
      <form onSubmit={handleSubmit}>
        <div>
          <label>Name: </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setNameInput(e.target.value)}
          />
        </div>
        <div>
          <label>Date of Birth: </label>
          <input
            type="date"
            value={dob}
            onChange={(e) => setDobInput(e.target.value)}
          />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default ChildComponent;

import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import ParentComponent from './components/ParentComponent';
import './App.css';

const App = () => {
  return (
    <Provider store={store}>
      <div className="app-container">
        <ParentComponent />
      </div>
    </Provider>
  );
};

export default App;

Initial State: The parent component’s user info div is visible but empty, with a fixed height to maintain the layout.
Submit Form in Child: After submitting the form, the parent component will display “Welcome, [name]! Your date of birth is [dob].” at the top.
State Persistence: The state (messages) will not persist after a refresh or a new load of the application, ensuring the messages are not visible when refreshed or the program is saved newly.

How to Ensure State Consistency When Using React Context and Asynchronous setState?

I want to maintain the filter values, which are key value pairs in a global context to support app wide state.

const createFilterContext = (defaultFilters: FilterState = {}) => {
const FilterContext = React.createContext<FilterContextType | undefined>(undefined);

const FilterProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [filters, setFilters] = React.useState<FilterState>(defaultFilters);

const setFilter = (key: string, value: any) => {
  setFilters((prevFilters) => ({ ...prevFilters, [key]: value }));
};

const clearFilters = () => {
  setFilters(defaultFilters);
};

return (
  <FilterContext.Provider value={{ filters, setFilter, clearFilters }}>
    {children}
  </FilterContext.Provider>
);
};

There is a filter panel which shows are the filter controls

const FilterPanel = ({ filterControls, onApply }: FilterPanelProps) => { }

<FilterPanel filterControls={filterControls} onApply={fetchDataWithFilters} />

FilterControls are some kind of input elements like dropdown, slider, checkbox etc.

onApply is passed by the pages that use FilterPanel. It will run when Apply Filters button in Filter Panel is clicked and will fetch Data with the applied key value pairs as query params to backend.

Now the problem here is React setState is asynchronous. So if I change some filter input control, and immediately click Apply Filters, the context state will be yet to update with the new value from that input control and makes fetch call without the new value.

My real code is much bigger and complex. I have simplified it here.
Please help me with your suggestions. Is my design bad? How can I solve this prolem?

intersection observer rootMargin not triggering callback

My goal is to trigger a callback when an element is within 500px of the viewport. However, the callback only triggers when the element actually enters or leaves the viewport, ignoring the rootMargin setting

here’s my code:

function handleIntersect(entries, observer) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        console.log('Box is intersecting with root');
      } else {
        console.log('Box is not intersecting with root');
      }
    });
  }

  function createObserver() {
    let observer;

    let options = {
      rootMargin: "500px 0px", // Extend the root's bounding box by 500px vertically
      threshold: 0             // Trigger the callback when any part of the element intersects
    };

    observer = new IntersectionObserver(handleIntersect, options);
    let boxElement = document.getElementById('boxElement');
    observer.observe(boxElement);
  }

  createObserver();
.spacer {
    height: 2000px;
  }
  .box {
    width: 100px;
    height: 100px;
    background-color: red;
    margin: 20px;
  }
  
  
  .as-console-wrapper {
    opacity: 0.5
  }
<div class="spacer"></div>
<div class="box" id="boxElement"></div>
<div class="spacer"></div>

Preview Gif showing that the intersection observer triggers as if no root margin would be set

I expect the handleIntersect callback to be triggered when the #boxElement is within 500px of entering or leaving the viewport…

However the callback only triggers when the element actually enters or leaves the viewport, ignoring the 500px root margin