Passing emit events to a global modal window VueJS

When i started this project a created a reusable global window component using a Pinia store. It has worked beautifully for me and I haven’t had any problems with it while working on the project for 2 months. All of my modals have been forms that don’t need acces to any outside reactive varaibles.

The problem:

I need a way to extend my component in a way so it can handle Vue event emits. This way the component is able to communicate to outside components.

The current component and its Pinia store:

import { defineStore } from "pinia";
import { ref } from "vue";
import { markRaw } from "vue";

const defaultState = { component: null, props: {} };

export const useModalStore = defineStore("modal", () => {
  const modalState = ref(defaultState);

  const openModal = ({ component, props }) => {
    modalState.value = { component: markRaw(component), props: props || {} };
  };

  const closeModal = () => {
    modalState.value = defaultState;
  };

  return { modalState, openModal, closeModal };
});
<script setup>
import { useModalStore } from "@stores/ModalStore";
import { storeToRefs } from "pinia";

const { closeModal } = useModalStore();
const { modalState } = storeToRefs(useModalStore());
</script>

<template>
  <Teleport to="#modals">
    <Transition name="modal-window-transition">
      <div
        class="modal-window__wrapper"
        @click.self="closeModal"
        v-if="modalState?.component"
      >
        <div class="modal-window">
          <component :is="modalState?.component" v-bind="modalState?.props" />
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

How is the component used?

First import the modalStore and the component u want in the modal. Then extract the openModal and or closeModal actions from the store. Call the appropriate action when for example a click event occours. You can pass props just fine using the props param.

import { useModalStore } from "@stores/ModalStore";

import BaseButton from "@components/BaseButton.vue";
import DishesModalCreate from "@components/DishesModalCreate.vue";

<BaseButton @click="openModal({ component: DishesModalCreate })"
  >Add dish
</BaseButton>

I’ll try to explain the problem I want to solve using an example. How can the ModalContent component update the parentValue ref trough an event.

Parent.vue
import { useModalStore } from "@stores/ModalStore";
import { ref } from "vue"

import ModalContent from "@components/ModalContent.vue";

const { openModal } = useModalStore();

const parentValue = ref("update me via modal")

<template>
  <button @click="openModal({component: ModalContent})"></button>
</template>
ModalContent.vue
<script setup>
const emits = defineEmits(['updateParentState'])
</script>

<template>
  <button @click="emit("updateParentState")"></button>
</template>

Possible solutions

I know you can pass functions as props in Vue but its considered as a bad practice that if possible I want to avoid.

Another option would be to use global state but That’s a bit overkill imo.

Hope this gives enough context to understand what I’m trying to achieve. Any insights are welcome thanks in advance!!

Variable not working when passed into function [duplicate]

In short when I define an element to a variable outside of a function using getElementById and try to do something with that variable inside of a function, it wont work. It only works if I explicitly run the getElementById command WITHOUT the variable. What am I missing?

The error is TypeError: nav is null

var nav = document.getElementById("navMenu")

function showMenu() {
  nav.style.right = '0' // doesn't work 
}

Mapbox – flyTo click reloads webpage

I used this Mapbox tutorial to build a map. When I load it in CodePen, it works as expected. When you click a listing from the left menu, it zooms to the location. However, when I put the map on a website, clicking a listing from the left menu either reloads the page or scrolls the page up to the top. I’ve experienced this behavior in Chrome, Firefox, and Safari on iOS.

I suspect it has something to do with the way it’s building the list:

      /* Add the link to the individual listing created above. */
      const link = listing.appendChild(document.createElement('a'));
      link.href = '#';
      link.className = 'title';
      link.id = `link-${location.properties.id}`;
      link.innerHTML = `${location.properties.project_site}`;

But everything I’ve tried to change there just breaks it.

I also realized going back to the Mapbox tutorial that I was using that when I click a listing on their map at the end of the page, the page also scrolls down a bit. So I assume it must be something in the original code and not something that I’ve changed?

Javascript how to target double quotes within double quotes.. and display them in browser

This is about retaining literal data in HTML via js writes in a browser.

Sample code…when I display this in Javascript, using document.write:

<html>
<script>

FULL = `
{
    "key": "something",
    "value": "{n    "theId": "our_id"}",
    "futureData": "{"myEvent":"\"UNCHANGED\"","myEventTimestamp":"\"2023-03-16T14:44:36.639\""}"
}
`           
; 
document.write('<pre>'+FULL+'</pre>'); 


</script>
</html>

In HTML, even if I wrap it around with <pre> it loses the slashes and messes around with the new line character, etc. How can I ensure the document.write does NOT lose the slashes and newline, and shows the data exactly as it’s in the codes? This is what it looks like:

{
    "key": "something",
    "value": "{
    "cdrId": "our_id"}",
    "futureData": "{"myEvent":""UNCHANGED"","myEventTimestamp":""2023-03-16T14:44:36.639""}"
}   

Some slashes are gone.. the newline character is gone.

Any ideas on how to retain the text with JS when printing in HTML? The way the code block does here on this website!

prompt momentListener is not triggering when use_fedcm_for_prompt is true

We are using Google One Tap prompt to signup/signin with Google account and initializing it as per the documentation. However, the momentListener is not triggering when use_fedcm_for_prompt is true but works fine if use_fedcm_for_prompt is false.

The GSI client library: https://accounts.google.com/gsi/client

We have below code:

google.accounts.id.initialize({
    callback: handleCredentialResponse,
    cancel_on_tap_outside: false,
    client_id: `<client_id>`,
    itp_support: true,
    use_fedcm_for_prompt: true,
});

google.accounts.id.renderButton(
    gsiButton.current as HTMLDivElement,
    renderGoogleButtonOptions
);

google.accounts.id.prompt((promptNotification) => {
    console.log('prompt callback', promptNotification);
});

In above code, the google.accounts.id.prompt‘s momentListener is never triggered. But disabling use_fedcm_for_prompt triggers the momentListener.

In documentation I found below notes:

Note: To improve user privacy, display moment notifications are intentionally delayed when FedCM is enabled. Notifications can be received up to 1 minute after the actual event took place.

Note: For the native credential manager, there is no notification for display, skipped, or dismissed moments as these occur outside of the GIS library.

Not sure whether the takeaway is momentListener never gets triggered or triggered after a delay. I waited 10mins after the One Tap popup is shown and still the momentListener wasn’t called.

Any ideas on how to get this working?

Problem with installing puppeteer and handlebars

While trying to install puppeteer and handlebars (npm i) an error occurs:

npm ERR! code EEXIST

npm ERR! syscall mkdir

npm ERR! path /Users/user/.npm/_cacache/content-v2/sha512/61/51

npm ERR! errno -13

npm ERR! EACCES: permission denied, mkdir '/Users/user/.npm/_cacache/content-v2/sha512/61/51'

npm ERR! File exists: /Users/user/.npm/_cacache/content-v2/sha512/61/51

npm ERR! Remove the existing file and try again, or run npm

npm ERR! with --force to overwrite files recklessly.

I’ve tried to reinstall node-modules but it didn’t work 🙁

I’m working on MacOS

Why my Switch Statement is returning Undefined . As it should be behaving like this? Weird JS [duplicate]

function reccursion(){
    let random=Math.floor(Math.random()*9);
    if(squares[random]==null){
// Here I'm getting the random between 0-8 range in console but in switch statement sometimes returning undefined
      console.log(random,'random value generated') 
      switch(random){
        case 0:
          return 0
        case 1:
          return 1
        case 2:
          return 2
        case 3:
          return 3
        case 4:
          return 4
        case 5:
          return 5
        case 6:
          return 6
        case 7:
          return 7
        case 8:
          return 8
      }
    }else{
      reccursion();
    }
}

Here I have created the recursive function where if any value of an square'( Array of length 9 and index is 0-8 )’ which is selected randomly is null so I should return its index no which is random value. But some times it is giving me undefine even after there is null value present in the square

Virtual keyboard moving the page

How can I prevent the virtual keyboard that appears in my web page from causing the page to scroll when clicking outside of an input field?

Currently, on some mobile devices, when the text field is filled and the keyboard is visible, clicking a button results in the keyboard disappearing faster than the click event can be registered.

This leads to unintentional clicks on other buttons, which is quite unexpected. I’ve attempted various solutions without success so far. Any suggestions or code snippets are greatly appreciated.

How to add click to go to next slide in this touch slider carousel

Currently the carousel goes from slide to slide through the use of sluding with your finger, but on top of that I want to add arrows that allow you to go from slide to slide, even if they are just apart of the logo image. Any ideas on how to implement this?

CSS:


ul,
body,
p {
  margin: 0;
  padding: 0;
}

.slider {
  box-sizing: border-box;
  background: black;
  width: 100vw;
  height: 55vh;
  overflow: hidden;
}

.slider .slides-container {
  display: flex;
  width: 100%;
  height: 100%;
  cursor: -webkit-grab;
  cursor: grab;
  transition: transform .5s;
}

.slider:active .slides-container {
  cursor: -webkit-grabbing;
  cursor: grabbing;
}

.slider .slides-container.moving {
  transition: none;
}

.slider .slides-container.moving .slide {
  transition: none;
}

.slider .slides-container.moving .parallax {
  transition: none;
}

.slider .slide {
  position: relative;
  display: block;
  width: 100%;
  height: 100%;
  background: #fff;
  opacity: .8;
  transform: scale(.9);
  transform-origin: center;
  transition: transform .5s, opacity .5s;
}

.slider .slide.current {
  opacity: 1;
  transform: scale(1);
}

.slider .slide .parallax {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  pointer-events: none;
  transition: transform .5s, opacity .5s;
}

.slider .slide.current .parallax {
  display: flex;
  opacity: 1;
  transform: translate3d(0, 0, 0);
}

.slider .slide .content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.slider .slide .parallax p {
  position: static;
  text-align: left;
  color: #000;
  font-size: 2.3em;
  justify-content: center;
  align-items: center;
  width: 77%
}

.slider .slide .parallax img {
  position: static;
  width: 35%;
  justify-content: center;
  align-items: center;
}

.slider .slide .parallax #TNYT {
  position: static;
  width: 35%;
  justify-content: center;
  align-items: center;
  padding-top: 15px;
}

.slider .slide .parallax #ESQUIRE {
  position: static;
  width: 40%;
  justify-content: center;
  align-items: center;
  margin-top: -10px;
}

.slider .slide .parallax #CNET {
  position: static;
  width: 35%;
  justify-content: center;
  align-items: center;
  padding-top: 15px;
  margin-bottom: -10px;
}

.slider .slide:nth-child(6n+2) {
  background: #fff;
}

.slider .slide:nth-child(6n+3) {
  background: #fff;
}

.slider .slide:nth-child(6n+4) {
  background: #fff;
}

.slider .slide:nth-child(6n+5) {
  background: #fff;
}

.slider .slide:nth-child(6n+6) {
  background: #fff;
}

HTML:

<div class="slider">
  <ul class="slides-container">
    <li class="slide">
      <div class="parallax">
        <div class="content">
          <p class="quote">“By eliminating middlemen and maintaining zero surplus stock,
            Kuze is able to offer its premium products at a more affordable price compared to other bespoke clothing
            brands, while still being Eco-friendly.”</p>
          <img class="logo" src="https://cdn.shopify.com/s/files/1/0758/3105/0520/files/GQ.png?v=1700523020" alt="">
        </div>
      </div>
    </li>
    <li class="slide">
      <div class="parallax">
        <div class="content">
          <p class="quote">“Say goodbye to ill-fitting clothes - no more drooping shoulders,
            rolled-up cuffs, or loose, baggy tops and stretched waists.
            With Kuze, every piece is tailored to fit you perfectly.”</p>
          <img id="TNYT" class="logo" src="https://cdn.shopify.com/s/files/1/0758/3105/0520/files/TNYT.png?v=1700523020" alt="">
        </div>
      </div>
    </li>
    <li class="slide">
      <div class="parallax">
        <div class="content">
          <p class="quote">“Kuze collaborates with leading fashion professionals and academic researchers to develop
            their
            Fit Recognition Engine®, ensuring a precise and personalized fit for every individual.”</p>
          <img id="ESQUIRE" class="logo" src="https://cdn.shopify.com/s/files/1/0758/3105/0520/files/Esquire.png?v=1700523020" alt="">
        </div>
      </div>
    </li>
    <li class="slide">
      <div class="parallax">
        <div class="content">
          <p class="quote">“the ultimate aim at Kuze is to boost the confidence of their customers by providing them
            with
            clothing that not only looks good but also feels great to wear.”</p>
          <img id="CNET" class="logo" src="https://cdn.shopify.com/s/files/1/0758/3105/0520/files/CNET.png?v=1700523020" alt="">
        </div>
      </div>
    </li>
    <li class="slide">
      <div class="parallax">
        <div class="content">
          <p class="quote">“At Kuze, each piece of clothing created is a unique masterpiece, tailored to ensure a
            precise
            fit. From incorporating your initials to meticulous tailoring, they ensure that every product is truly
            one-of-a-kind.”</p>
          <img class="logo" src="https://cdn.shopify.com/s/files/1/0758/3105/0520/files/Details.png?v=1700523020" alt="">
        </div>
      </div>
    </li>
  </ul>
</div>

JS:

/**
* Code by Noé Falque ➡️ noe.im
**/

class Slider {
  constructor(el) {

    this.el = el
    this.container = this.el.querySelector('.slides-container')
    this.slides = this.container.querySelectorAll('.slide')
    this.parallaxes = this.container.querySelectorAll('.parallax')

    this.current = 0;
    this.currentPos
    this.mouseOffset
    this.moving = false

    this.container.style.width = this.slides.length * 100 + '%'
    this.slides[0].classList.add('current')

    let startPos, lastTouchX

    const

      dragStart = (e) => {
        e.stopPropagation()
        if (e.touches) lastTouchX = e.touches[0].clientX
        startPos = e.clientX || lastTouchX
        this.mouseOffset = 0
        this.currentPos = this.container.getBoundingClientRect().left;
        this.moving = true;
        requestAnimationFrame(this.move.bind(this))
      },

      dragEnd = (e) => {
        if (this.moving) {
          const moveX = e.clientX || lastTouchX
          if (moveX < startPos - 100) this.next()
          else if (moveX > startPos + 100) this.prev()
          else this.goTo(this.current)
          this.moving = false
        }
      },

      dragMove = (e) => {
        if (e.touches) lastTouchX = e.touches[0].clientX
        const moveX = e.clientX || lastTouchX
        this.mouseOffset = moveX - startPos
      }

    this.container.addEventListener('mousedown', dragStart)
    this.container.addEventListener('touchstart', dragStart)

    window.addEventListener('mouseup', dragEnd)
    this.container.addEventListener('touchend', dragEnd)

    window.addEventListener('mousemove', dragMove)
    this.container.addEventListener('touchmove', dragMove)

    window.addEventListener('keydown', (e) => {
      e = e || window.event;
      if (e.keyCode == '39') {// right arrow
        this.next()
      }
      else if (e.keyCode == '37') {// left arrow
        this.prev()
      }
    })

  }

  move() {
    if (this.moving) {
      this.container.style.transform = 'translate3d(' + (this.currentPos + this.mouseOffset) + 'px, 0, 0)'
      this.container.classList.add('moving')
      const slideWidth = this.slides[0].offsetWidth;
      this.slides.forEach(($_slide, i) => {
        const coef = 1 - Math.abs($_slide.getBoundingClientRect().left / slideWidth)
        $_slide.style.opacity = .5 + (coef * .5)
        $_slide.style.transform = 'scale(' + (.9 + coef * .1) + ')'
      })
      this.parallaxes.forEach(($_item, i) => {
        const coef = this.slides[i].getBoundingClientRect().left / slideWidth
        $_item.style.opacity = 1 - Math.abs(coef * 1.8)
        $_item.style.transform = 'translate3d(' + (-coef * 85) + '%, 0, 0)'
      })
      requestAnimationFrame(this.move.bind(this))
    }
  }

  goTo(i) {
    if (i >= 0 && i < this.slides.length) this.current = i
    this.container.classList.remove('moving')
    this.container.style.transform = 'translate3d(' + this.current * -100 / this.slides.length + '%, 0, 0)'

    this.slides.forEach(($_slide, i) => {
      $_slide.classList.remove('current')
      $_slide.removeAttribute('style')
    })
    this.slides[this.current].classList.add('current')
    this.slides[this.current].removeAttribute('style')

    this.parallaxes.forEach(($_item, i) => {
      $_item.removeAttribute('style')
      $_item.style.transform = 'translate3d(' + (i <= this.current ? 85 : -85) + '%, 0, 0)'
    })
    this.slides[this.current].querySelector('.parallax').removeAttribute('style')
  }

  next() {
    this.goTo(this.current + 1)
  }

  prev() {
    this.goTo(this.current - 1)
  }

}

const $sliders = document.querySelectorAll('.slider')
const sliders = []
$sliders.forEach(($slider) => {
  sliders.push(new Slider($slider))
})

I tried to add an image of an arrow and build radio functionality but unfortunatly i keep messing up.

How to use multiple HTML buttons in CSS and display the value in a text input [duplicate]

I am trying to get multiple values of the buttons displayed next to each other in “field2” when you select them. I could not find out how to combine them in a working way…

function myFunction() {
  document.getElementById("field2").value = document.getElementById("field1").value;
}
<!DOCTYPE html>
<html>

<body>

  <input class="calculator" type="button" id="field1" value=1 onclick="myFunction()">
  <input class="calculator" type="button" id="field1" value=2 onclick="myFunction()">
  <input class="calculator" type="button" id="field1" value=3 onclick="myFunction()"><br>
  <input class="calculator" type="button" id="field1" value=4 onclick="myFunction()"> .....
  <br> Code: <input type="text" id="field2"><br><br>

</body>

</html>

Create and download .py file by clicking HTML button

I am writing HTML and Javascript code for a chatbot. When the chatbot returns a python program, I want a download button to appear. When I click this Download button, I want to create a .py file from this output and download it.

The following is the code that I have written.

{% extends "layout.html" %}
{% block content %}

<!-- Begin page content -->
  <div class="overflow-auto">
    <br>
    <br>

    <div id="list-group" class="list-group w-auto">
      <a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">                                                           
        <img src="https://digital-practice.ams3.cdn.digitaloceanspaces.com/static%2Fapp%2Fimg%2Fopenai-logo.png" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0"> 
        <div class="d-flex gap-2 w-100 justify-content-between">
          <div>
            <p class="mb-0 opacity-75">Hello, I am the chatbot for the AI4EIC Hackathon. How may I help you?</p>
          </div>
        </div>
      </a>
    </div>
    <div class="input-group mb-3">
      <textarea id="chat-input" class="form-control custom-control" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
      <span id="gpt-button" class="input-group-asson btn btn-primary">Ask ChatGPT</span>
    </div>
  </div>

  <script>
    $("gpt_button").attr("disabled", true);
  </script>

  <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

  <script>

    $("#gpt-button").click(function(){
    chat();
    });

    $("#chat-input").keypress(function(event){  
    if(event.which==13){
        chat();
    }
    });

    function download(data){

    const blob = new Blob([data], {type:"application/x-python-code"});

    const href = URL.createObjectURL(blob);
    URL.revokeObjectURL(href);

    const a = Object.assign(document.createElement('a'), {href, style:"display:none", download: "program.py"});
    document.body.appendChild(a);

    a.click();
    URL.revokeObjectURL(href);
    a.remove();
    
    }
    
    function chat(){
    var question = $("#chat-input").val();
    console.log("Test");    
    $("#chat-input").val('');


    
    let html_data = '';
    html_data += `<a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">
        <img src="{{ url_for('static', filename='images/ai4eic-logo.png') }}" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">
        <div class="d-flex gap-2 w-100 justify-content-between">
          <div>
            <p class="mb-0 opacity-75">${question}</p>
          </div>
        </div>
      </a>`;
    $("#chat-input").val('');
    $("#list-group").append(html_data);

    $.ajax({
        type: "POST",
        url: "/chat",
        data: {'prompt': question},
        success: function (data) {

        let gpt_data = '';
        gpt_data += `

               <style> 
                       p{word-break: break-all;
                         white-space:normal;} 

                       #download-button {
                         transition: opacity 1s;
                         opacity: 0;
                        }

                       #download-button.fadeIn {
                         opacity: 1;
                         }
                </style>       


           <a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">
                    <img src="https://digital-practice.ams3.cdn.digitaloceanspaces.com/static%2Fapp%2Fimg%2Fopenai-logo.png" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">  
                    <div class="d-flex gap-2 w-100 justify-content-between">
                      <div class="a">                                                           
                        <p class="mb-0 opacity-75">${data.answer}</p>    
                        <button onclick="download(${data.answer})" type="button" disabled="${!(String(data.answer).includes("```python"))}" id="download-button" class="btn btn-primary ${String(data.answer).includes("```python") ? 'fadeIn' : ''}">Download Code</button>                
                      </div>                                                          
                    </div>                                                            
                  </a>`;
        $("#list-group").append(gpt_data);
        }
    });
    };

    </script>
 

{% endblock content %}

I am able to get the Download button to appear when the chatbot returns a python program. However, the code does not work after I have added the download function:

function download(data){

    const blob = new Blob([data], {type:"application/x-python-code"});

    const href = URL.createObjectURL(blob);
    URL.revokeObjectURL(href);

    const a = Object.assign(document.createElement('a'), {href, style:"display:none", download: "program.py"});
    document.body.appendChild(a);

    a.click();
    URL.revokeObjectURL(href);
    a.remove();
    
}

I want this to be triggered by the download button, which I have written as such

 <button onclick="download(${data.answer})" type="button" disabled="${!(String(data.answer).includes("```python"))}" id="download-button" class="btn btn-primary ${String(data.answer).includes("```python") ? 'fadeIn' : ''}">Download Code</button> 

Why is my array returning the commas when I use slice()?

I’m trying to do this coding challenge that takes a list and an index and returns the values in increments of the index. for example…

combo([1, 2, 3, 4], 2) ➞ [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

when I try to grab the values it also grabs the commas and messes up the code. It’s currently returning 1,23,4 and so on.

let newList = [];

function nCombo(list, index) {
  let newIndex = 0 + index;
  for (i = 0; list.length >= i; i += index) {
    newList.join(list.slice(i, newIndex));
    console.log(`slice = ${list.slice(i,newIndex)}`)
    console.log(newList);
    newIndex += index;
  }
  console.log(newList);
}

nCombo([1, 2, 3, 4, 5, 6], 2)

I tried to use join before I was using newList += list.slice(i , newIndex);

I don’t know why it’s doing this

Antd Time RangePicker Exclude specific datetimes

I’m finding it very unclear if what I’m trying to do is possible out of the box with ant design. I have an array of moment ranges:

[ {  start: Moment(), end: Moment()  } ... ]

And I have a basic picker in a form

const { RangePicker } = TimePicker;

<Form.Item name="location-datetime">
  <RangePicker
    showTime={{ format: 'hh:mm A' }}
    format="hh:mm A"
  />
</Form.Item>

For my specific case, date dosn’t matter because the times that I’ll be working with will always be on the same day. My objective is to simply disable any times that are already present in any of the date ranges in my array. So if I have a range from 4am to 10:30 am, I should still be able to a start/end time of 10:45, but not 10:20. The idea is I don’t want my users choosing a range that’s already “being used”.

But I’m not seeing a way to do that without creating my own complex logic, and this really seems like something that would have been figured out at some point before, I’m not trying to reinvent the wheel here.

How can I use disabledDate or disabledTime to disable these time ranges in my picker?

Error: Maximum update depth exceeded. NextJs

I have a Next.js component that’s throwing an ‘Error: Maximum update depth exceeded.’ It mentions that this error can occur when a component repetitively calls setState inside componentWillUpdate or componentDidUpdate. React restricts the number of nested updates to prevent infinite loops

"use client";
import fakeData from "../MOCK_DATA.json";
import { useTable } from "react-table";
import * as React from "react";

export default function App() {
  const data = React.useMemo(() => fakeData, []);
  const columns = React.useMemo(() => [
    {
      Header: "ID",
      accessor: "id",
    },
    {
      Header: "Primeiro Nome",
      accessor: "first_name",
    },
    {
      Header: "Último Nome",
      accessor: "last_name",
    },
    {
      Header: "Email",
      accessor: "email",
    },
    {
      Header: "Genero",
      accessor: "gender",
    },
    {
      Header: "IP Address",
      accessor: "ip_address",
    },
  ]);

  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
    useTable({ columns, data });

  return (
    <div>
      <div>
        <table {...getTableProps()}>
          <thead>
            {headerGroups.map((headerGroup) => (
              <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => (
                  <th {...column.getHeaderProps()}>
                    {column.render("Header")}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody {...getTableBodyProps()}>
            {rows.map((row) => {
              prepareRow(row);
              return (
                <tr {...row.getRowProps()}>
                  {row.cells.map((cell) => (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  ))}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

. I’m having trouble understanding why this is happening. Can anyone help me out?

I am trying to get a method to work and it isn’t passing a test like I expected [closed]

I am trying to make this Ant work method work but it is not returning the quantity of ants correctly. I have supplies pictures of the failing test and my code.

screenshot of failing test

code

I have tried different forms of the method and the rest of the code, where this my latest try where all tests are passing minus the 1 that isn’t. I am not sure how to get the correct string.