Uncaught (in promise) Error: Credential is missing

I have this simple form executed into React page:

import React, {useState} from 'react';
import { Link } from 'react-router-dom';
import {LambdaClient, InvokeCommand, LogType} from "@aws-sdk/client-lambda"; // ES Modules import
const { fromTemporaryCredentials } = require("@aws-sdk/credential-providers");


const FooterOne = ({ footerLight, style, footerGradient }) => {

  const handleSubmit = async (event) => {
    event.preventDefault();

    const credentials = await fromTemporaryCredentials({
      params: {
        RoleArn: "arn:aws:lambda:us-east-1:123456789:function:email-submit",
      },
      clientConfig: {
        region: 'us-west-2',
      },
    })();

    try {
      const client = new LambdaClient({
        region: 'us-west-2',
        credentials,
      });

      const command = new InvokeCommand({
        FunctionName: "email-submit",
        Payload: JSON.stringify("payload"),
        LogType: LogType.Tail,
      });

      const { Payload, LogResult } = await client.send(command);
      const result = Buffer.from(Payload).toString();
      const logs = Buffer.from(LogResult, "base64").toString();
      return { logs, result };
    } catch (error) {
      console.error('Error invoking function:', error);
      // Handle errors as needed
    }
  };

  return (
      <>
        <form onSubmit={handleSubmit}>
          <input
              type='text'
              placeholder='Enter your email'
              name='email'
              required=''
              autoComplete='off'
          />
          <input
              type='submit'
              value='Subscribe'
              data-wait='Please wait...'
          />
        </form>
      </>
  );
};

export default FooterOne;

Lambda code into AWS Lambda:

export const handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

But I get error:

Uncaught (in promise) Error: Credential is missing
    at SignatureV4.credentialProvider (runtimeConfig.browser.js:22:1)
    at SignatureV4.signRequest (SignatureV4.js:103:1)
    at SignatureV4.sign (SignatureV4.js:58:1)
    at awsAuthMiddleware.js:24:1
    at async retryMiddleware.js:27:1
    at async loggerMiddleware.js:3:1
    at async fromTemporaryCredentials.js:20:1
    at async handleSubmit (FooterOne.js:12:1)

Do you know how I can fix this issue?

FullCalendar ReactJS Timeline View

I have this Reactjs FullCalendar that i used to assign shifts to the staffs as seen in the snippet

Snippet

But the problem is that as seen from above it gets clustured into one and does not look good so i want to put it in such a way that the name are on the yaxis so if a staff has a shift at 6am shift at 1st dec, on 1st dec corresponding to the staffs name only 6am will be written there. So basically i want something like the excel sheet below.

SHIFT

So is there any way to make my table like this as the excel or any react table template or table exist like this as i already have an array just need a table like this or fill in.

Here is my code if needed https://pastecode.io/s/3u9qjzyi

thanks in advance

Already tried with the above snippet as shown but no luck

Used fullcalendar api

I have tried with FullCalendar Timeline View as seen via this link https://fullcalendar.io/docs/timeline-view as this exactly matches what i want to have but after following this document and putting it on my own it says that resourceTimelinePlugin not found.

html2canvas is not loading images inside the component

I have the following component on React with NextJs13:

import React, { useRef } from 'react';
import html2canvas from 'html2canvas';

const StoryCard = ({ children, color }) => {
  // Para compartir como imagen
  const storyCardRef = useRef();
  const shareStoryCard = async () => {
    try {
      const canvas = await html2canvas(storyCardRef.current);
      const image = canvas.toDataURL('image/png');
      const blob = await (await fetch(image)).blob();

      if (navigator.share) {
        await navigator.share({
          files: [new File([blob], 'storycard.png', { type: 'image/png' })],
          title: 'Check out my favorite anime genres!',
        });
      } else {
        // Alternativa para navegadores que no soportan compartir archivos
        const link = document.createElement('a');
        link.href = image;
        link.download = 'storycard.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    } catch (error) {
      throw new Error('Error sharing the story card:', error);
    }
  };
  // Para guardar la imagen
  const saveStoryCard = async () => {
    try {
      const canvas = await html2canvas(storyCardRef.current);
      const image = canvas.toDataURL('image/png');

      // Crear un enlace para la descarga
      const link = document.createElement('a');
      link.href = image;
      link.download = 'storycard.png'; // o podrías usar un nombre de archivo dinámico si lo prefieres
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      throw new Error('Error saving the story card:', error);
    }
  };
  return (
    <div>
      <div ref={storyCardRef} id="series-story" className={`story story--${color}-gradient`}>
        <div className="story__content">
          {children}
        </div>
        <div className="story__footer">
          <p className="story__footer-link">animanga-wrapped.vercel.app</p>
        </div>
      </div>
      <div className="story__button-container">
        <button type="button" onClick={shareStoryCard} className="story__button">Share</button>
        <button type="button" onClick={saveStoryCard} className="story__button">Save</button>
      </div>
    </div>
  );
};

StoryCard.displayName = 'StoryCard';

export default StoryCard;

Some of the children props contain images hosted on Cloudinary. Everything is working well BUT the images. They are not included on the final image generated by html2canvas. Everything is OK: fonts, css styles, etc. But the image isn’t there. Only the space.

Any ideas?

What does “host” mean in this MDN reference article about globalThis?

I was reading about globalThis in the MDN documentation, specifically here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

In the Description section, the first note says:

globalThis is generally the same concept as the global object (i.e. adding properties to globalThis makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for globalThis that’s unrelated to the global object.

I just want a clarification from native english speakers and programmers that are expert in JS about the meaning of “hosts” in this context, because I’m not getting it.

I don’t think the host definition from the MDN glossary applies here – it seems way to broad to me and does not help me understand when could I find globalThis changed in its nature.

There is not much that I could try, since it is a matter of text comprehension.

Filter() Array by results

let students = [
    {
        name: 'John',
        subjects: ['maths', 'english', 'cad'],
        teacher: {maths: 'Harry', english: 'Joan', cad: 'Paul'},
        results: {maths: 90, english: 75, cad: 87},
    },
    {
        name: 'Emily',
        subjects: ['science', 'english', 'art'],
        teacher: {science: 'Iris', english: 'Joan', art: 'Simon'},
        results: {science: 93, english: 80, art: 95},
    },
    {
        name: 'Adam',
        subjects: ['science', 'maths', 'art'],
        teacher: {science: 'Iris', maths: 'Harry', art: 'Simon'},
        results: {science: 84, maths: 97, art: 95},
    },
    {
        name: 'Fran',
        subjects: ['science', 'english', 'art'],
        teacher: {science: 'Iris', english: 'Joan', art: 'Simon'},
        results: {science: 67, english: 87, art: 95},
    }
];

const topMaths = students.filter((student) => student.results >= 90);
console.log(topMaths);

I’m new enough to this and couldn’t find the answer online.

Why won’t the students with over 90 come out in the console.
It shows empty [].

react setState not retaining previous state

I am trying to build an infinite scroll loader component, but somehow my ‘items’ array resets to [] (emptying) instead of appending the new results as I would expect.

A couple of things to note:

  1. I see the API calls in the network tab when the observer comes into view.
  2. the data returned by the API is fresh and unique (no cache issues)

This is the relevant line:
setItems([...items, ...data.data]); // items is resetting to [], data.data is always a new set of fresh values

"use client";
import { useState, useEffect, useRef } from "react";

export function HBSInfiniteScrollList({ request = {} }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const observerTarget = useRef(null);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await fetch(request.url, request.options);
      if (res.ok) {
        const data = await res.json();        
        setItems([...items, ...data.data]);
      } else {
      }
    } catch (err) {
      console.log(err);
      setError(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          console.log("isIntersecting, fetching new data...");
          fetchData();
        }
      },
      { threshold: 1 }
    );

    if (observerTarget.current) {
      observer.observe(observerTarget.current);
    }

    return () => {
      if (observerTarget.current) {
        observer.unobserve(observerTarget.current);
      }
    };
  }, [observerTarget]);

  return (
    <div>
      <ul className="list-group">
        {items.map((item) => (
          <li key={item.id} className="list-group-item">
            {item.name}
          </li>
        ))}
      </ul>
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      length: {items.length}
      <div ref={observerTarget}></div>
    </div>
  );
}

Anyone see anything wrong with it? I have written this type of code a million times. Maybe I am just tired.

Updater function not working in variable context api – react native

Please help, I am creating a survey system. Each survey will have an undetermined number of questions, so their painting is done dynamically, that is, if it is type select, text, numeric, etc… for each one I render a different component. Now, I have created a ResponsesContext, a context to have the responses of the different modules or/or surveys globally, in such a way that when I leave a module and later return again, it loads the responses that the user already had filled out. .

In context I have the following code:

import React from "react";

const RespuestasContext = React.createContext();

//Provider
const RespuestasProvider = ({ children }) => {

    const [respuestas, setRespuestas] = React.useState({});

    const manejadorRespuestas = (modulo, codPregunta, respuesta) => {
        let tmp_respuestas = respuestas

        if (tmp_respuestas.hasOwnProperty(modulo)) {
            //Actualizar      
            if (tmp_respuestas[modulo].hasOwnProperty(codPregunta)) {
                tmp_respuestas[modulo][codPregunta] = {
                    respuesta
                }
            } else {
                insertar({ modulo, codPregunta, respuesta })
            }

        } else {
            //Insertar
            insertar({ modulo, codPregunta, respuesta })
        }
        setRespuestas(tmp_respuestas);

        return respuestas;
    }

    const insertar = (data) => {

        let tmp_respuestas = respuestas

        const { modulo, codPregunta, respuesta } = data

        if (tmp_respuestas.hasOwnProperty(modulo)) {
            tmp_respuestas[modulo][codPregunta] = {
                respuesta
            }
        } else {
            tmp_respuestas[modulo] = {
                [codPregunta]: {
                    respuesta
                }
            }
        }
        setRespuestas(tmp_respuestas);
    }

    const data = {
        respuestas,
        manejadorRespuestas     
    }

    return <RespuestasContext.Provider value={data}>{children}</RespuestasContext.Provider>;
}
export { RespuestasProvider };//themeProvider
export default RespuestasContext;//themecontext

In the component where I paint the form I have something like this:

const { respuestas, manejadorRespuestas } = useContext(RespuestasContext);

    renderQuestions = ({ item, index }) => {

        if (item.TIPO_CONTROL == 'text') {

            manejadorRespuestas(item.ID_MODULO, item.CODIGO, '')
            console.log('ping => ',respuestas[item.ID_MODULO][item.CODIGO].respuesta)

            return (
                <InputText
                    label={item.DESCRIPCION}
                    value={respuestas[item.ID_MODULO][item.CODIGO].respuesta}
                    onChange={(value) => {
                        manejadorRespuestas(item.ID_MODULO, item.CODIGO, value)
                        console.log('respuestas ', respuestas)
                    }}
                />
            )
        }
}

Every time the value of the input changes, the updater function updates the values in the responses variable of the context, but for some reason, when I access it in the value, like this: value={respuestas[item.ID_MODULO][item.CODIGO].respuesta} the change is not reflected, it simply deletes the field again, therefore the value in the context variable always has a letter that is the first character that I type in the input as seen in the console:
[![enter image description here][1]][1]

If I want to write “Barrio el prado” for example, writing the first letter “B” calls the updater function… I don’t know what could be causing this problem.

The “NOMBRE DEL BARRIO O VEREDA” field is question code 556 as seen in the console.

[![enter image description here][2]][2]

Thanks for your help.
[1]: https://i.stack.imgur.com/WJthz.png
[2]: https://i.stack.imgur.com/L2aug.png

How to trigger full screen on web without user gesture/interaction

I am creating a web game that requires to be automatically on full screen on startup but browsers put a security restriction whereby full screen API can only be initiated on user action or gesture
Is there any way I can bypass this?

I have tried every possible way but it keeps saying in console “full screen API can only be initiated by user gesture

How to display a javascript object as hex data in console.log

I am an embedded C developer, but there is some TypeScript (javascript?) code that performs various hash and sign operations. I am trying to compare what it is generating to what happens in C on another platform to make them compatible. Unfortunately, I cannot figure out any way to dump the object to the terminal as simple hex data using something like console.log(). As you may have figured out, I am not a javascript developer.

CodePen UI Scrolling Wheel Datepicker bug

I’m using code from this CodePen and on desktop, it works fine. However, when I open it on a mobile phone and scroll the middle column with months, when I get to month 6, all items below and above disappear. The same issue occurs with the days column; on day 6 and 16, everything above and below disappears. It seems there is a bug after 5 and 10 elements. Can someone take a look at the code and try to find a solution for why this is happening? Thanks.

I initially thought the problem might be in this part, but it seems that’s not the case:

[...this.elems.circleItems].forEach(itemElem => {
  if (Math.abs(itemElem.dataset.index - scroll) > this.quarterCount) {
    itemElem.style.visibility = 'hidden';
  } else {
    itemElem.style.visibility = 'visible';
  }
});

I tried to inspect elements and change CSS but nothing works.

Responsive list inside a modal (React)

the CSS has been really hard on me lately. So I am trying to make a modal that would have a scrollable list inside of it however the issue is that when I decrease the height of the browser window some of the list items are hidden from the view, also the button beneath the list is invisible and it should stay there no matter the position of the list. Can you help out, please and if possible explain what I am doing wrong here? Thanks

CodeSandbox

Bluebeam auto complete text box based on previous text box input

I have a 14 page pdf document with a header that contains various fields that repeat on each page. I want to have the second, third, fourth, and so on pages to auto populate the header information the same as the info inputted on the first page. I am not familiar with this stuff at all and have gotten as far as I have with only this communities help.

I am using the following script…

var selected = this.getField(“Project Number”);

Have also tried…

var selectedTask = this.getField (“Project Number”);

as well as numerous other variations. Simply put, I want to have the end user fill in the Project Number (and various other items) in the first field and have the same number automatically populate throughout the remainder of the document.

I have also attempted to name the fields the same and copy and paste them to have them all be completed at once. This approach does not work in Bluebeam.

Grateful for your help.

How can I determine whether an array is a prototype?

Checking is a value is an array is straight forward in JavaScript:

Array.isArray(value);

However, I need to distinguish between a value that is an array and a value that is andarray and also an array prototype. For instance:

Array.isArray([]); // true
Array.isArray(Object.getPrototypeOf([])); // true, but need false

Unfortunately the prototype of arrays is also type array, which is why Array.isArray returns true in this example.

If anyone knows how I can differentiate between the two (test for arrays, but not array prototypes) it would be greatly appreciated.

Error in filters (Out os Stock / in Stock)

i have filters option in my shopify store, when i click in stock then the Url will change but it not show the in stock product but when i refresh the page my function is call, how can i fix this
here is my code

window.onload = function(){
  class FacetFiltersForm extends HTMLElement {
    constructor() {
      super();
      this.onActiveFilterClick = this.onActiveFilterClick.bind(this);
  
      this.debouncedOnSubmit = debounce((event) => {
        this.onSubmitHandler(event);
      }, 500);
  
      const facetForm = this.querySelector('form');
      facetForm.addEventListener('input', this.debouncedOnSubmit.bind(this));
  
      const facetWrapper = this.querySelector('#FacetsWrapperDesktop');
      if (facetWrapper) facetWrapper.addEventListener('keyup', onKeyUpEscape);
    }
  
    static setListeners() {
      const onHistoryChange = (event) => {
        const searchParams = event.state ? event.state.searchParams : FacetFiltersForm.searchParamsInitial;
        if (searchParams === FacetFiltersForm.searchParamsPrev) return;
        FacetFiltersForm.renderPage(searchParams, null, false);
      };
      window.addEventListener('popstate', onHistoryChange);
    }
  
    static toggleActiveFacets(disable = true) {
      document.querySelectorAll('.js-facet-remove').forEach((element) => {
        element.classList.toggle('disabled', disable);
      });
    }
  
    static renderPage(searchParams, event, updateURLHash = true) {
      FacetFiltersForm.searchParamsPrev = searchParams;
      const sections = FacetFiltersForm.getSections();
      const countContainer = document.getElementById('ProductCount');
      const countContainerDesktop = document.getElementById('ProductCountDesktop');
      document.getElementById('ProductGridContainer').querySelector('.collection').classList.add('loading');
      if (countContainer) {
        countContainer.classList.add('loading');
      }
      if (countContainerDesktop) {
        countContainerDesktop.classList.add('loading');
      }
  
      sections.forEach((section) => {
        const url = `${window.location.pathname}?section_id=${section.section}&${searchParams}`;
        const filterDataUrl = (element) => element.url === url;
  
        FacetFiltersForm.filterData.some(filterDataUrl)
          ? FacetFiltersForm.renderSectionFromCache(filterDataUrl, event)
          : FacetFiltersForm.renderSectionFromFetch(url, event);
      });
  
      if (updateURLHash) FacetFiltersForm.updateURLHash(searchParams);
    }
  
    static renderSectionFromFetch(url, event) {
      fetch(url)
        .then((response) => response.text())
        .then((responseText) => {
          const html = responseText;
          FacetFiltersForm.filterData = [...FacetFiltersForm.filterData, { html, url }];
          FacetFiltersForm.renderFilters(html, event);
          FacetFiltersForm.renderProductGridContainer(html);
          FacetFiltersForm.renderProductCount(html);
          if (typeof initializeScrollAnimationTrigger === 'function') initializeScrollAnimationTrigger(html.innerHTML);
        });
    }
  
    static renderSectionFromCache(filterDataUrl, event) {
      const html = FacetFiltersForm.filterData.find(filterDataUrl).html;
      FacetFiltersForm.renderFilters(html, event);
      FacetFiltersForm.renderProductGridContainer(html);
      FacetFiltersForm.renderProductCount(html);
      if (typeof initializeScrollAnimationTrigger === 'function') initializeScrollAnimationTrigger(html.innerHTML);
    }
  
    static renderProductGridContainer(html) {
      document.getElementById('ProductGridContainer').innerHTML = new DOMParser()
        .parseFromString(html, 'text/html')
        .getElementById('ProductGridContainer').innerHTML;
  
      document
        .getElementById('ProductGridContainer')
        .querySelectorAll('.scroll-trigger')
        .forEach((element) => {
          element.classList.add('scroll-trigger--cancel');
        });
    }
  
    static renderProductCount(html) {
      const count = new DOMParser().parseFromString(html, 'text/html').getElementById('ProductCount').innerHTML;
      const container = document.getElementById('ProductCount');
      const containerDesktop = document.getElementById('ProductCountDesktop');
      container.innerHTML = count;
      container.classList.remove('loading');
      if (containerDesktop) {
        containerDesktop.innerHTML = count;
        containerDesktop.classList.remove('loading');
      }
    }
  
    static renderFilters(html, event) {
      const parsedHTML = new DOMParser().parseFromString(html, 'text/html');
  
      const facetDetailsElements = parsedHTML.querySelectorAll(
        '#FacetFiltersForm .js-filter, #FacetFiltersFormMobile .js-filter, #FacetFiltersPillsForm .js-filter'
      );
      const matchesIndex = (element) => {
        const jsFilter = event ? event.target.closest('.js-filter') : undefined;
        return jsFilter ? element.dataset.index === jsFilter.dataset.index : false;
      };
      const facetsToRender = Array.from(facetDetailsElements).filter((element) => !matchesIndex(element));
      const countsToRender = Array.from(facetDetailsElements).find(matchesIndex);
  
      facetsToRender.forEach((element) => {
        document.querySelector(`.js-filter[data-index="${element.dataset.index}"]`).innerHTML = element.innerHTML;
      });
  
      FacetFiltersForm.renderActiveFacets(parsedHTML);
      FacetFiltersForm.renderAdditionalElements(parsedHTML);
  
      if (countsToRender) FacetFiltersForm.renderCounts(countsToRender, event.target.closest('.js-filter'));
    }
  
    static renderActiveFacets(html) {
      const activeFacetElementSelectors = ['.active-facets-mobile', '.active-facets-desktop'];
  
      activeFacetElementSelectors.forEach((selector) => {
        const activeFacetsElement = html.querySelector(selector);
        if (!activeFacetsElement) return;
        document.querySelector(selector).innerHTML = activeFacetsElement.innerHTML;
      });
  
      FacetFiltersForm.toggleActiveFacets(false);
    }
  
    static renderAdditionalElements(html) {
      const mobileElementSelectors = ['.mobile-facets__open', '.mobile-facets__count', '.sorting'];
  
      mobileElementSelectors.forEach((selector) => {
        if (!html.querySelector(selector)) return;
        document.querySelector(selector).innerHTML = html.querySelector(selector).innerHTML;
      });
  
      document.getElementById('FacetFiltersFormMobile').closest('menu-drawer').bindEvents();
    }
  
    static renderCounts(source, target) {
      const targetElement = target.querySelector('.facets__selected');
      const sourceElement = source.querySelector('.facets__selected');
  
      const targetElementAccessibility = target.querySelector('.facets__summary');
      const sourceElementAccessibility = source.querySelector('.facets__summary');
  
      if (sourceElement && targetElement) {
        target.querySelector('.facets__selected').outerHTML = source.querySelector('.facets__selected').outerHTML;
      }
  
      if (targetElementAccessibility && sourceElementAccessibility) {
        target.querySelector('.facets__summary').outerHTML = source.querySelector('.facets__summary').outerHTML;
      }
    }
  
    static updateURLHash(searchParams) {
      history.pushState({ searchParams }, '', `${window.location.pathname}${searchParams && '?'.concat(searchParams)}`);
    }
  
    static getSections() {
      return [
        {
          section: document.getElementById('product-grid').dataset.id,
        },
      ];
    }
  
    createSearchParams(form) {
      const formData = new FormData(form);
      return new URLSearchParams(formData).toString();
    }
  
    onSubmitForm(searchParams, event) {
      FacetFiltersForm.renderPage(searchParams, event);
    }
  
    onSubmitHandler(event) {
      event.preventDefault();
      const sortFilterForms = document.querySelectorAll('facet-filters-form form');
      if (event.srcElement.className == 'mobile-facets__checkbox') {
        const searchParams = this.createSearchParams(event.target.closest('form'));
        this.onSubmitForm(searchParams, event);
      } else {
        const forms = [];
        const isMobile = event.target.closest('form').id === 'FacetFiltersFormMobile';
  
        sortFilterForms.forEach((form) => {
          if (!isMobile) {
            if (form.id === 'FacetSortForm' || form.id === 'FacetFiltersForm' || form.id === 'FacetSortDrawerForm') {
              const noJsElements = document.querySelectorAll('.no-js-list');
              noJsElements.forEach((el) => el.remove());
              forms.push(this.createSearchParams(form));
            }
          } else if (form.id === 'FacetFiltersFormMobile') {
            forms.push(this.createSearchParams(form));
          }
        });
        this.onSubmitForm(forms.join('&'), event);
      }
    }
  
    onActiveFilterClick(event) {
      event.preventDefault();
      FacetFiltersForm.toggleActiveFacets();
      const url =
        event.currentTarget.href.indexOf('?') == -1
          ? ''
          : event.currentTarget.href.slice(event.currentTarget.href.indexOf('?') + 1);
      FacetFiltersForm.renderPage(url);
    }
  }
  
  FacetFiltersForm.filterData = [];
  FacetFiltersForm.searchParamsInitial = window.location.search.slice(1);
  FacetFiltersForm.searchParamsPrev = window.location.search.slice(1);
  customElements.define('facet-filters-form', FacetFiltersForm);
  FacetFiltersForm.setListeners();
  
  class PriceRange extends HTMLElement {
    constructor() {
      super();
      this.querySelectorAll('input').forEach((element) =>
        element.addEventListener('change', this.onRangeChange.bind(this))
      );
      this.setMinAndMaxValues();
    }
  
    onRangeChange(event) {
      this.adjustToValidValues(event.currentTarget);
      this.setMinAndMaxValues();
    }
  
    setMinAndMaxValues() {
      const inputs = this.querySelectorAll('input');
      const minInput = inputs[0];
      const maxInput = inputs[1];
      if (maxInput.value) minInput.setAttribute('max', maxInput.value);
      if (minInput.value) maxInput.setAttribute('min', minInput.value);
      if (minInput.value === '') maxInput.setAttribute('min', 0);
      if (maxInput.value === '') minInput.setAttribute('max', maxInput.getAttribute('max'));
    }
  
    adjustToValidValues(input) {
      const value = Number(input.value);
      const min = Number(input.getAttribute('min'));
      const max = Number(input.getAttribute('max'));
  
      if (value < min) input.value = min;
      if (value > max) input.value = max;
    }
  }
  
  customElements.define('price-range', PriceRange);
  
  class FacetRemove extends HTMLElement {
    constructor() {
      super();
      const facetLink = this.querySelector('a');
      facetLink.setAttribute('role', 'button');
      facetLink.addEventListener('click', this.closeFilter.bind(this));
      facetLink.addEventListener('keyup', (event) => {
        event.preventDefault();
        if (event.code.toUpperCase() === 'SPACE') this.closeFilter(event);
      });
    }
  
    closeFilter(event) {
      event.preventDefault();
      const form = this.closest('facet-filters-form') || document.querySelector('facet-filters-form');
      form.onActiveFilterClick(event);
    }
  }


  customElements.define('facet-remove', FacetRemove);
}

I’m expecting the results. can some one suggest me what the the possibility to do this, how can I solve this
thanks

Stimulus controller action fires twice on click

For some reason, my stimulus controller, load once, but the action is fired twice on click.
I can’t find where the issue is…

My code is pretty simple though, so I will share it below:

// app/javascript/application.js
https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"

// app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"
const application = Application.start()
application.debug = false
window.Stimulus   = application
export { application }
// app/javascript/controllers/index.js
import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
// app/javascript/controllers/radio_button_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static classes = [ 'active', 'inactive', 'invisible' ]

  connect() {
    console.log('connected to ', this.element.querySelector('input').value)
  }

  markAsChecked(event) {
    event.stopPropagation();
    console.log('-', this.element.querySelector('input').value);
  }
}
// view.html.erb

<div class="flex flex-1 gap-x-8 justify-start">
  <label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
    <input type="radio" value="public" name="destination[access_type]" id="destination_access_type_public">
  </label>
  <label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
    <input type="radio" value="private" name="destination[access_type]" id="destination_access_type_private">
  </label>
  <label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
    <input type="radio" value="backend" name="destination[access_type]" id="destination_access_type_backend">
  </label>
</div>

When I run the following commands in the developer console, I also get double action firing

// developer console
temp1 // label
temp1.click()
// - public
// - public
temp2 // input
temp2.click()
// - public

As you can see, markAsChecked is triggered twice when I click on the label, and once when I click on the input. I have no idea why…
(I expect it to always trigger once)