How do I generate a new with the exercise properties when an exercise is selected from the modal in my react native app

I am trying to create an exercise app that generates a new view. Within that view, users will be able to input weight and sets. In my code I have a modal that generates a list of exercises from a different file. I would then like to select an exercise which should populate a new view in the return with properties of the selected exercise.

Here is the code I have so far

import React, { useState } from 'react';
import { View, ScrollView, Modal, Picker, Text, TouchableOpacity, TextInput, StyleSheet, Button, FlatList  } from 'react-native';
import myExerciseList from './ExerciseList';
//import Exercise from './ExerciseSets';

const exercises = myExerciseList

const ExerciseList = () => {
  const [views, setViews] = useState([]);
  const [visible, setVisible] = useState(false);

  const handlePress = () => {
    const newView = <View style={styles.ExerciseBox} key={views.length} >
                      <Text>Exercise</Text>
                    </View>;
    setViews([...views, newView]);
    setVisible(false);
  };

  return (
    <View>
      {/* Render the views */}
      {views}

      {/* Add a new view */}
      <TouchableOpacity onPress={() => setVisible(true)}>
          <Text>Select an Exercise</Text>
        </TouchableOpacity>
        <Modal visible={visible}>
          <ScrollView>
            {exercises.map((item) => (
              <TouchableOpacity key={item.id} onPress={() => handlePress(item)}>
                <Text>{item.name}</Text>
              </TouchableOpacity>
            ))}
            <TouchableOpacity onPress={() => setVisible(false)}>
              <Text>Cancel</Text>
            </TouchableOpacity>
          </ScrollView>
        </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  ExerciseBox: {
    flexDirection: 'column',
    borderWidth: 2,
    borderRadius: 5
  },

})


export default ExerciseList;

I have tried creating another hook which then transfers the properties of the selected exercise to the handlePress function but I get the error
NewExercise.js:14 Uncaught ReferenceError: item is not defined
at handlePress

Am I missing something or is my approach completely wrong?

How to put my slashcommands in only patreon users

I searching all comments how to make commands only for patreon users on discord but they are all obsolete and/or old and they do not work for me and I would like to know if there is a possibility or not to do it anymore

This my command

const { EmbedBuilder, SlashCommandBuilder, PermissionFlagsBits, VoiceChannel, GuildEmoji} = require('discord.js');
const client = require("../../index");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("forward")
    .setDescription(`adelanta en segundos la cancion en curso`)
    .addIntegerOption(option =>
        option.setName('segundos')
        .setDescription('adelanta la cancion')
        .setMinValue(0)
        
        .setRequired(true)),
                        async execute(interaction) {
                           

            
            
    
                            const {member, guild, options, client} = interaction;

                            
                            
                            const seconds = options.getInteger("segundos");
                            const voiceChannel = member.voice.channel;

                             const embed = new EmbedBuilder();

                            if(!voiceChannel) {
                                embed.setColor("Red")
                                .setDescription("Necesitas estar en un canal de voz para ejecucarme");
                                return interaction.reply({ embeds: , ephemeral: true});
                            }
                            if (interaction.guild.members.me.voice.channel && interaction.member.voice.channel.id !== interaction.guild.members.me.voice.channel.id) {embed.setColor("Red")
                                 .setDescription(`<:YuyukoPistolaPS:1078353755189297202>Oye ya me solicitaron en <#${guild.members.me.voice.channelId}>`);
                                return interaction.reply({ embeds: , ephemeral: true});
                            }

                            try {
                                const queue = await client.distube.getQueue(voiceChannel);

                                            if(!queue) {
                                                embed.setColor("Red")
                                        .setDescription('No estoy reproducciendo la lista de reproduccion');
                                        return interaction.reply({ embeds: , ephemeral: true});
                                            }
                                
                                            await queue.seek(queue.currentTime + seconds);
                                                embed.setColor("Green")
                                                .setDescription(`Cancion adelantada por `${seconds}``);
                                                return interaction.reply({ embeds: });

                            } catch (err) {
                                console.log(err);
                                embed.setColor("Red")
                                .setDescription(`Algo ha pasado...`);
                                return interaction.reply({ embeds: , ephemeral: true});
                            }
                        }
                    }

I expecting if is possible convert this command in only patreon users or no

js eventlistener for mouse hover not working

I am trying to add an event listener so that each grid will change color when the mouse hovers over it. but its not working. the event listener just before it works, and i tried to use console.log()to see if this part of the code runs and it does. any help appreciated.

code pen:
https://codepen.io/minifo/pen/rNZpEgG

code snippet in question:

    const items = document.querySelectorAll('.item');

    items.forEach(item => {
        item.addEventListener('mouseover', () => {
          item.style.backgroundColor = 'red';
        });
      });

I tried to add an eventlistener for mouseenter that will change the hovered-over grid to red. but it’s not working.

Error: Unsupported image type / Canvas “Background” || Discord.js V.14

This is my code:

const { createCanvas, loadImage } = require('canvas');

...

// Generate welcome image with user's icon
    const canvas = createCanvas(700, 250);
    const ctx = canvas.getContext('2d');
    const user = interaction.member.user;
    const avatar = await loadImage(user.displayAvatarURL({ format: 'png', size: 256 }));
    const background = await loadImage("https://cdn.discordapp.com/attachments/105735240637265978831/108420311910335197234/image.png"); // Replace with your own background image URL
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2 - 30, 80, 0, Math.PI * 2);
    ctx.closePath();
    ctx.clip();
    ctx.drawImage(avatar, canvas.width / 2 - 80, canvas.height / 2 - 110, 160, 160);
    ctx.restore();
    ctx.fillStyle = '#ffffff';
    ctx.font = '36px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(user.username, canvas.width / 2, canvas.height / 2 + 60);
    ctx.font = '24px Arial';
    ctx.fillText(message, canvas.width / 2, canvas.height / 2 + 90);

In the console it replies with:

SetSource.call(img, src)
            ^
Error: Unsupported image type

I checked if the URL in here loadImage("...") is compatible with Canvas and it is (.png). I reinstalled canvas to see if there were any errors but it didn’t work. Some might say that this post is similar to others but trying the other solutions does not work. Any answer is accepted! Thanks!!

Why option element not appending inside both select tag only appending at last select tag?

Html

<div class="from">
            <select name="" class="droplistOptions">
             <!--insert option element here-->
            </select>
          </div>
          <p class="to-seprator">To</p>
          <div class="to">
            <select name="" class="droplistOptions">
               <!--insert option element here also -->
            </select>
          </div>

Javascript Code

const droplists = document.querySelectorAll(".droplistOptions");
countryNames = ['usa','India','china','japan']
 countryNames.forEach((country) => {
    const optionElement = document.createElement("option");
    optionElement.value = country;
    optionElement.textContent = country;
    droplists.forEach((item) => item.append(optionElement));

});

In above Code I want to insert all countries names from countryNames array as option element inside the both select tag in html but when i am using append it only append the option element in last or 2nd select tag inside html and first select tag is empty there is no option element inserted inside first select tag.I don’t know what mistake I am doing.I want to understand why it’s working like this it should append optionElement at both place in select tag because droplists is nodelist array and forEach iterating each element so

To get selected radio button in react for updation of form

import React, {useState, useEffect} from 'react'
import axios from 'axios'
import clsx from 'clsx'
import Swal from 'sweetalert2'

const GroupsUpdateModal = ({AgetIdFromLooping}) => {
  const [AgroupUpdateData, setAgroupUpdateData] = useState({
    accessGroupId: AgetIdFromLooping,
    accessGroupName: '',
    requestReceivingMechanism: '',
    itGroup: null,
    createdOn: '2023-02-16',
    createdBy: '1',
  })

  const GroupsUpdateModal_handleChange = (e) => 
  {
    setAgroupUpdateData(({...AgroupUpdateData, [e.target.name]: e.target.value}))
  }

  const GroupsUpdateModal_handleCheck = (e) => 
  {
    setAgroupUpdateData({...AgroupUpdateData, [e.target.name]: e.target.checked})
  }

  const GroupsUpdateModal_updateGroupModalForm = (e) => 
  {
    e.preventDefault()
    try 
    {
      axios
        .put(`${process.env.REACT_APP_API_URL}help/update`, AgroupUpdateData, 
        {
          headers: 
          {
            'Content-Type': 'application/json',
            Authorization: localStorage.getItem('token'),
          },
        })
        .then(async (res) => 
        {
          console.log('update groups', res.data)
          if (res.status === 201) 
          {
            await Swal.fire({
              title: 'Are you sure?',
              text: `You want to Save the changes! `,
              icon: 'warning',
              buttons: true,
              showDenyButton: true,
              confirmButtonText: 'Yes',
              denyButtonText: `No`,
            }).then(async (result) => 
            {
              if (result.isConfirmed) 
              {
                await Swal.fire(` Updated successfully!`, '', 'success')
                window.location.reload()
              } else 
              {
                await Swal.fire('No changes has been saved!', '', 'info')
              }
            })
          }
          console.log(
            'groups update modal form updated successfully -- success ==> GroupsUpdateModal_updateGroupModalForm',
            res.data
          )
        })
    } catch (error) 
    {
      console.error(
        'groups update modal form   error ==> GroupsUpdateModal_updateGroupModalForm',
        error
      )
      Swal.fire(`Error ${error}`, 'Form submission failed!', 'error')
      throw error
    }
  }

  const GroupsUpdateModal_getDataById = (AgetIdFromLooping) => 
  {
    try 
    {
      axios
        .get(`${process.env.REACT_APP_API_URL}help/${id}`, 
        {
          headers: 
          {
            'content-type': 'application/json',
            Authorization: localStorage.getItem('token'),
          },
        })
        .then((res) => 
        {
          let result = res.data
          setAgroupUpdateData(result)
          console.log(
            'get update group data based on id -- success  ==> GroupsUpdateModal_getDataById',
            result
          )
        })
    } catch (error) 
    {
      console.error(
        'get update group data based on id -- error ==> GroupsUpdateModal_getDataById',
        error
      )
      throw error
    }
  }

  useEffect(() => 
  {
    GroupsUpdateModal_getDataById(AgetIdFromLooping)
  }, [AgetIdFromLooping])

  return (
    <div
      class='modal modal-static fade'
      data-bs-backdrop='static'
      id='kt_modal_add_group'
      tabindex='-1'
      aria-hidden='true'
    >
      <div class='modal-dialog modal-dialog-centered mw-650px'>
        <div class='modal-content'>
          <div class='modal-header'>
            <h2 class='fw-bold'>Update Group</h2>
            <div class='btn btn-icon btn-sm btn-active-icon-primary' data-bs-dismiss='modal'>
              <span class='svg-icon svg-icon-1'>
                <svg
                  width='24'
                  height='24'
                  viewBox='0 0 24 24'
                  fill='none'
                  xmlns='http://www.w3.org/2000/svg'
                >
                  <rect
                    opacity='0.5'
                    x='6'
                    y='17.3137'
                    width='16'
                    height='2'
                    rx='1'
                    transform='rotate(-45 6 17.3137)'
                    fill='currentColor'
                  />
                  <rect
                    x='7.41422'
                    y='6'
                    width='16'
                    height='2'
                    rx='1'
                    transform='rotate(45 7.41422 6)'
                    fill='currentColor'
                  />
                </svg>
              </span>
            </div>
          </div>
          <div class='modal-body scroll-y mx-5 mx-xl-15 my-7'>
            <form
              id='kt_modal_add_task_form'
              class='form'
              onSubmit={GroupsUpdateModal_updateGroupModalForm}
              noValidate
            >
              <div class='fv-row mb-7'>
                <label class='required fs-6 fw-semibold form-label mb-2'> Group name</label>
                <input
                  placeholder='Group name'
                  type='text'
                  name='accessGroupName'
                  onChange={GroupsUpdateModal_handleChange}
                  value={AgroupUpdateData?.accessGroupName}
                  className={clsx(
                    'form-control form-control-solid mb-3 mb-lg-0'
                  )}
                  autoComplete='off'
                />
              </div>
              <div class='fv-row mb-7'>
                <label class='fs-6 fw-semibold form-label mb-2'>
                  <span class='required'>Receive requests based on</span>
                </label>
                <div className='d-flex justify-content-between'>
                  <div className='d-flex fv-row'>
                    <div className='form-check form-check-custom form-check-solid'>
                      <input
                        className='form-check-input me-3'
                        type='radio'
                        name='requestReceivingMechanism'
                        checked={AgroupUpdateData.requestReceivingMechanism === 1}
                        onChange={GroupsUpdateModal_handleChange}
                        value={AgroupUpdateData.requestReceivingMechanism === 1}
                        id='kt_modal_update_role_option_0'
                      />
                      <label className='form-check-label' htmlFor='kt_modal_update_role_option_0'>
                        <div className='fw-bolder text-gray-800'>Load Balancing Mechanism</div>
                      </label>
                    </div>
                  </div>
                  <div className='d-flex fv-row'>
                    <div className='form-check form-check-custom form-check-solid'>
                      <input
                        className='form-check-input me-3'
                        type='radio'
                        checked={AgroupUpdateData.requestReceivingMechanism === 2}
                        onChange={GroupsUpdateModal_handleChange}
                        id='kt_modal_update_role_option_1'
                        value={AgroupUpdateData.requestReceivingMechanism === 2}
                        name='requestReceivingMechanism'
                      />
                      <label className='form-check-label' htmlFor='kt_modal_update_role_option_1'>
                        <div className='fw-bolder text-gray-800'>Priority & Attendance</div>
                      </label>
                    </div>
                  </div>
                </div>
              </div>
              <div class='fv-row mb-7'>
                <div className='d-flex fv-row'>
                  <div className='form-check form-check-custom form-check-solid'>
                    <input
                      className='form-check-input me-3'
                      type='checkbox'
                      name='itGroup'
                      onChange={GroupsUpdateModal_handleCheck}
                      defaultChecked={AgroupUpdateData?.itGroup}
                      // value={AgroupUpdateData.itGroup}
                      id='kt_modal_update_role_option_3'
                    />
                    <label className='form-check-label' htmlFor='kt_modal_update_role_option_3'>
                      <div className='fw-bolder text-gray-800'>is IT Group</div>
                    </label>
                  </div>
                </div>
              </div>
              <div class='text-center pt-15'>
                <button type='reset' class='btn btn-light me-3' data-bs-dismiss='modal'>
                  Cancel
                </button>
                <button type='submit' class='btn btn-primary' data-kt-users-modal-action='submit'>
                  <span class='indicator-label'>Save</span>
                  <span class='indicator-progress'>
                    Please wait...
                    <span class='spinner-border spinner-border-sm align-middle ms-2'></span>
                  </span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
}

export default GroupsUpdateModal

this is my code of popup modal for updating form and i am getting selected radio button for first time and when i click on cancel button without doing any change and but for the second time i am not getting any selected radio button. And also i when i select another radio button to update the form the radio button is not checked but after saving it i get the value of radio button.What will be the issue in it? Can anybody help me?
Thanks

How do I create a bar graph using a FOR-loop using JavaScript, CSS and HTML only?

I’m trying to create a bar chart using JavaScript and HTML but the chart is not displaying correctly. It doesn’t look like a bar chart. I’m not sure what I’m doing wrong. The only thing that displays are the values. How can I make it work without using an external JS file (reusing someone else’s code)? This is for an intro to JavaScript course and I have to use a div instead of a canvas.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bar Chart</title>

    <style>
        #chart {
            width: 100%;
            max-width: 600px;
            background-color: aliceblue;
            display: block;
        }
        .bar{
            background: green;
        }
        .exceed{
            background: blueviolet;
        }

    </style>

</head>
<body> 
        <div id="chart"></div>

<script>
 and variables

const DPOINTS = 400;
const MAX = 300;
const EXCEED = 0.8;
let c;
let value;

let chart = document.getElementById("chart");

for (let c =0; c <= DPOINTS; c++){

 value = Math.abs(Math.cos(c/180 * Math.PI) * MAX + MAX);   

 let div = document.createElement("DIV");
 div.style.height = 5 + 'px';
 div.style.width = value;
 div.classList.add("bar");

 if (value > MAX * EXCEED) {
  div.classList.add("exceed");
 
 }
 div.innerHTML = value;

 chart.appendChild(div);
}
</script>

   <script src="chart2.js"></script>


</body>
</html>

The outcome is supposed to look similar to this: expected outcome

JS: Deep Searching a value within nesting of objects and array not working?

I have two functions findInObj and findInArray that tries to match/find a value for e.g ldfzjeyfuvbkcjccztn (needle) within a nesting of objects and arrays (HAYSTACK) and returns the PARENT object OR FALSE, recursively calling itself where appropriate. Somehow the setup dosen’t work, though the value is in the HAYSTACK.

HAYSTACK

{
    "slide1":
    {
        "uid": 1672503300574,
        "zones": [
        {
            "imgData":
            {
                "size": 84764,
                "id": 10,
                "name": "Universe.png",
                "type": "image/png",
                "imageStyles":
                {},
                "previewElement":
                {
                    "class": "dz-preview dz-complete dz-image-preview"
                }
            },
            "uid": 1648468065257,
            "caption": "BBBBBefore",
            "captionStyles":
            {
                "left": "41px",
                "objectFitClassName": "object-fit-fill",
                "top": "42px"
            },
            "arrowStyles":
            {},
            "childZoneId": 0,
            "styles":
            {
                "height": "327px",
                "left": "109px",
                "objectFitClassName": "object-fit-fill",
                "top": "518px",
                "width": "421px"
            },
            "canvasElementType": "photo"
        },
        {
            "imgData":
            {
                "size": 29161,
                "id": 13,
                "name": "water_treatment_plant.png",
                "type": "image/png",
                "imageStyles":
                {},
                "previewElement":
                {
                    "class": "dz-preview dz-complete dz-image-preview"
                }
            },
            "uid": 1648468065580,
            "caption": "AAAAfter",
            "captionStyles":
            {
                "height": "39px",
                "left": "28px",
                "objectFitClassName": "object-fit-fill",
                "top": "-1px",
                "width": "140px"
            },
            "arrowStyles":
            {},
            "childZoneId": 1,
            "styles":
            {
                "height": "517px",
                "left": "1083px",
                "objectFitClassName": "object-fit-fill",
                "top": "491px",
                "width": "536px"
            },
            "canvasElementType": "photo"
        }],
        "headings": [
        {
            "elemStyles":
            {
                "height": "92px",
                "left": "413px",
                "top": "28px",
                "width": "498px"
            },
            "title": "First TextBox",
            "titleStyles":
            {
                "height": "92px",
                "left": "415px",
                "objectFitClassName": "object-fit-fill",
                "top": "26px",
                "width": "498px"
            },
            "uid": "ldfzjesz45rh6v5lvoi"
        },
        {
            "elemStyles":
            {
                "height": "116px",
                "left": "191px",
                "top": "231px",
                "width": "282px"
            },
            "title": "Secoooond TextBox",
            "titleStyles":
            {
                "height": "116px",
                "left": "191px",
                "objectFitClassName": "object-fit-fill",
                "top": "231px",
                "width": "282px"
            },
            "uid": "ldfzjeub9zix7yuajmj"
        },
        {
            "elemStyles":
            {
                "height": "87px",
                "left": "766px",
                "top": "445px",
                "width": "181px"
            },
            "title": "Fourth",
            "titleStyles":
            {
                "height": "87px",
                "left": "766px",
                "objectFitClassName": "object-fit-fill",
                "top": "445px",
                "width": "181px"
            },
            "uid": "ldfzjevsbu0mj71e5s"
        },
        {
            "elemStyles":
            {
                "height": "92px",
                "left": "180px",
                "top": "384px",
                "width": "367px"
            },
            "title": "Funny or DIE",
            "titleStyles":
            {
                "height": "92px",
                "left": "670px",
                "objectFitClassName": "object-fit-fill",
                "top": "159px",
                "width": "367px"
            },
            "uid": "ldfzjewwy2vnqnvwqda"
        },
        {
            "elemStyles":
            {
                "height": "97px",
                "left": "38px",
                "top": "47px",
                "width": "315px"
            },
            "title": "Infinity",
            "titleStyles":
            {
                "height": "97px",
                "left": "38px",
                "objectFitClassName": "object-fit-fill",
                "top": "47px",
                "width": "315px"
            },
            "uid": "ldfzjeyfuvbkcjccztn"
        }],
        "slideWrapperStyles": {},
        "duration": 5000,
    }
}

Func – Find In OBJECT

export function findInObj(obj, needle) {
  for(var key in obj) {
      var val = obj[key]
 
    //if ITEM is an Array
    if(val instanceof Array) {
      let retVal = findInArray(val, needle, obj)
      if(retVal) return retVal
    }

    //If ITEM is an Object
    if(val instanceof Object && !(val instanceof Array)) {
      return findInObj(val, needle)
    } else {

    //Neither Object or Array
      if(val == needle) {
          return obj
      }
    }
  }
  //Return `false` when the no item matches
  return false
}

Func – Find In ARRAY

export function findInArray(arr, needle, obj) {
  console.log("arr", arr);
  
  for(var item of arr) {
    
    //if item is an array
    if(item instanceof Array) {
      let retVal = findInArray(item, needle, obj)
      if(retVal) return retVal
    }
    
    //If Item is an Object
    if(item instanceof Object && !(item instanceof Array)) {
      let retVal = findInObj(item, needle)
      if(retVal) return retVal
    }
    
    //If Item is `anything`other than Array/Object
    if(item == needle) {
      return obj
    }
  }
  return false
}

I am not able to really pin-point the issue/problem in either of the functions but IMO, in findInObj where there is an object that doesn’t have either object or Array then the function just returns false and ends there. In other words the properties adjacent/at the same level to the nested object (that doesn’t have an object/array) within aren’t even checked.

Please help make both these functions work irrespective of at what level the value is.

How can I comprehend json data and correspondences?

I was trying to get sports projections off this site: https://api.prizepicks.com/projections ,
but the output of my code doesn’t seem to make sense.

I tried to read the data on the site using the following code:

import pandas as pd
import requests
from pandas import json_normalize

params = (
    ('league_id', '7'),
    ('per_page', '250'),
    ('projection_type_id', '1'),
    ('single_stat', 'true'),
)

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"

}
session = requests.Session()
response = session.get('https://api.prizepicks.com/projections', data=params, headers=headers)
print(response.status_code)

df1 = json_normalize(response.json()['included'])
df1 = df1[df1['type'] == 'new_player']

df2 = json_normalize(response.json()['data'])

df = pd.DataFrame(zip(df1['attributes.name'], [a[:10] for a in df2['attributes.board_time']], df2['attributes.line_score']), columns=['name', 'date', 'points'])
print(df.loc[df['date'] == '2023-03-11'])

However the output gives projections that don’t make sense for the players, meaning that somewhere in-between I’m mixing up the projections and the players they correspond to (ex. 18 goals for a soccer player). I tried reading the raw data to figure it out, but I’m completely lost, as I have no familiarity with json.

Memory cost of storing a Date object vs integer

I’m creating a web-based game with Node.js and I need to keep track of a number of timers for each player. I’m deciding between storing date objects for each timer and storing an integer representing the number of loops and based on an estimate of the game loop speed.

Is the date object method efficient enough or is the efficiency gain of the other method worth less accuracy? The longer the timer the less accurate it becomes with the integer method. The date method seems much more readable and maintainable, just wondering about scalability issues.

Example game loop:

player.action = () => {
  cooldown = new Date(Date.now() + 2000);
}

setInterval(() => {
  if (cooldown < Date.now())
    //do stuff
  }
}, 40);

vs

player.action = () => {
  cooldown = 50;
}

setInterval(() => {
  if (cooldown-- === 0)
    //do stuff
  }
}, 40);

Find unknow source of JS notification

I have a PWA, that uses firebase for notifications, but when I get the background notifications, I get an extra notification. It does not have the icon I specify or the “Background” addition in front of the title. I have no idea where it is coming from, except that it has to be in this set of code. I can comment out everything except the initializing stuff at the top and the const messaging = firebase.messaging(); and I still get it.

I tried setting my own messaging.onMessage to catch that incase there was a default (which there wasn’t upon inspection).

Can someone help me track down the source of this annoying notification?

importScripts('https://www.gstatic.com/firebasejs/9.6.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.2/firebase-messaging-compat.js');

var firebaseConfig = {
    apiKey: "REDACTED",
    authDomain: "REDACTED",
    projected: "REDACTED",
    storageBucket: "REDACTED",
    messagingSenderId: "REDACTED",
    appId: "REDACTED"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();


/////////////////////////
// The notification comes from the stuff above ^
/////////////////////////

self.addEventListener('notificationclick', function(event){
  const urlToOpen = new URL(REDACTED, self.location.origin).href;
  const promiseChain = clients.matchAll({
    type: 'window',
    includeUncontrolled: true
  })
  .then((windowClients) => {
    let matchingClient = null;

    for (let i = 0; i < windowClients.length; i++) {
      const windowClient = windowClients[i];
      if (windowClient.url === urlToOpen) {
        matchingClient = windowClient;
        break;
      }
    }

    if (matchingClient) {
      return matchingClient.focus();
    } else {
      return clients.openWindow(urlToOpen);
    }
  });

  event.waitUntil(promiseChain);

});


messaging.onMessage((e)=> console.log("FBsw:",e))

messaging.onBackgroundMessage(function(payload) {
  self.registration.showNotification("Background:"+payload.notification.title,
      {body: payload.notification.body,icon: REDACTED});
});

referenceError: require is not defined (Node)

I dont know whats going on. Cant find the solution through a google search. Any ideas here? I just want to be able to console.log the tools.fetch so I can see data in dev tools.

This is what I am trying to fetch ( https://www.npmjs.com/package/otter-api )

1.) JS

tools = require('otter-api');

tools.fetch().then(l => console.log(l))

2.) HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <script src="script.js"></script>
</body>
</html>

3.) In terminal: (this will create packagejson, node_module folders)
npm i

and then…

npm install otter-api

4.) ENDING COMMENT
I tried chnaging variable names, added const fs = require(‘fs’) thinking that would initiate something.

important question, just how there is an npx react install to set up the entire foundation for a react file, if there also one for when working with a node project to avoid stuff like this?

How to add dynamic search bar?

I have created an array and render items in flatlist. Now I have to add a searchbar on which if I press the 19 it shows me all the plans/data which consist of 19 (i.e, 19,219,119…etc).

Here is my code..
Due to formatting issues I am not able to add my code, please consider this link

Why are my two values undefined after the first HTTP request?

I am new to JavaScript, and I’m trying to retrieve input name for a city, for which to show temperature, country, weather description, and local time.

For this, I have planned on using the first API to retrieve the forecast, and the second to retrieve the local time by using the latitude and longitude from the first one.

Looks like the global variables latitude and longitude do not get the values in time, because when I console.log them separately they appear, but not when I need them for the second request

const HttpInfoRequest = new XMLHttpRequest();
const HttpTimeRequest = new XMLHttpRequest();

let city, countryCode, temperature, description, latitude, longitude, localTime;

const key = "9b9314b8382b45a5978468be7db26b82";
const url = "https://api.weatherbit.io/v2.0/current?city=";

const timeUrlKey = "RDHZPHTCVSQ2";
const timeUrl = "http://api.timezonedb.com/v2.1/get-time-zone?key=RDHZPHTCVSQ2&format=json&by=position&lat=40.689247&lng=-74.044502";

const countryAbbreviations = "https://github.com/samayo/country-json/blob/master/src/country-by-abbreviation.json";

let submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", function (event) {
    let inputValue = document.getElementById("city").value;
    HttpInfoRequest.open("GET", url + inputValue + "&key=" + key);
    HttpInfoRequest.send();
    console.log(latitude, longitude);
    HttpTimeRequest.open("GET", timeUrl + "?key=" + timeUrlKey + "&format=json&by=position&lat=" + latitude + "&lng="+ longitude);
    HttpTimeRequest.send();
});

HttpInfoRequest.onreadystatechange = function () {
    if (HttpInfoRequest.readyState == 4 && HttpInfoRequest.status < 300) {
        var responseArray = JSON.parse(HttpInfoRequest.responseText);

        console.log(responseArray);

        city = responseArray.data[0].city_name;
        countryCode = responseArray.data[0].country_code;
        temperature =  responseArray.data[0].temp;
        description = responseArray.data[0].weather.description;
        latitude = responseArray.data[0].lat;
        longitude = responseArray.data[0].lon;
        console.log(latitude, longitude);

        document.getElementById("cityResult").innerHTML = city + ", " + countryCode;
        document.getElementById("temperatureResult").innerHTML = temperature;
        document.getElementById("weatherDescription").innerHTML = description;
    }
};

HttpTimeRequest.onreadystatechange = function () {
    if (HttpTimeRequest.readyState == 4 && HttpTimeRequest.status < 300) {
        var responseArray = JSON.parse(HttpTimeRequest.responseText);

        console.log(responseArray);

    }
};

//TRIVIAL STUFF, IGNORE THIS
$(document).ready(function () {
    $("#darkModeToggle").click(function () {
        $("html").toggleClass("dark");
    });
});

window.onload = function () {
    if (window.jQuery) {
        console.log(
            "jQuery is working,",
            Math.floor(Date.now() / 31536000 / 1000) + " years since 1970"
        );
    } else {
        alert("jQuery fail");
    }
};

I attached the Developer Tools console results as an image in the following link:

Dev Tools console

Thank you in advance, I am excited about JavaScript but also kind of scared of it!