random button is not working as expected (React)

ok so im working on my first project in react, and im facing trouble with random button that i created.

enter image description here

the random button on the navbar supposed to generate numbers and insert it to the values of the inputs, and then the block changes it color by the values.
what happens is that it generate the values to the inputs on the first click, and then on the second click it changes the block color and the inputs.
so what happens is that the inputs matches the color of the next click.

export const ColorsProvider = (props) => {
  const [color, setColor] = useState("");
  const [red, setRed] = useState("");
  const [green, setGreen] = useState("");
  const [blue, setBlue] = useState("");
  const [colors, setColors] = useState([]);

  const changeColor = () => {
    if (
      red < 0 ||
      red > 255 ||
      green < 0 ||
      green > 255 ||
      blue < 0 ||
      blue > 255 ||
      !red ||
      !green ||
      !blue
    ) {
      console.log("Input must be between 0 and 255");
    } else {
      setColor(`rgb(${red}, ${green}, ${blue})`);
      setColors([...colors, color]);
    }
  };

  return (
    <ColorsContext.Provider
      value={{
        colorValue: [color, setColor],
        redValue: [red, setRed],
        greenValue: [green, setGreen],
        blueValue: [blue, setBlue],
        colorsArr: [colors, setColors],
        clickHandler: changeColor,
      }}
    >
      {props.children}
    </ColorsContext.Provider>
  );
};
function Navbar() {
  const {
    colorValue,
    redValue,
    greenValue,
    blueValue,
    colorsArr,
    clickHandler,
  } = useContext(ColorsContext);
  const [color, setColor] = colorValue;
  const [red, setRed] = redValue;
  const [green, setGreen] = greenValue;
  const [blue, setBlue] = blueValue;
  const [colors, setColors] = colorsArr;
  const changeColor = clickHandler;

  const generateNewColorOnClick = () => {
    service.ColorsService.getRandomColor().then((color) => {
      setColor(color.color);
      let colorArray = color.color.split(",");
      setRed(colorArray[0]);
      setGreen(colorArray[1]);
      setBlue(colorArray[2]);
      changeColor();
    });
  };

  return (
    <section>
      <div className="navbar-dark">
        <div>
          <a href="javascript:window.location.reload(true)">
            <h1>Color Generator</h1>
          </a>
        </div>

        <div>
          <a className={"href"} onClick={generateNewColorOnClick}>
            <h2>Random</h2>
          </a>
        </div>
      </div>
    </section>
  );
}
function ChooseColor() {
  const {
    colorValue,
    redValue,
    greenValue,
    blueValue,
    colorsArr,
    clickHandler,
  } = useContext(ColorsContext);
  const [color, setColor] = colorValue;
  const [red, setRed] = redValue;
  const [green, setGreen] = greenValue;
  const [blue, setBlue] = blueValue;
  const [colors, setColors] = colorsArr;
  const changeColor = clickHandler;

  return (
    <div className={"home"}>
      <section>
        <div className="container">
          <div>
            <p>Choose a color</p>
          </div>
          <div className="container-box" style={{ backgroundColor: color }} />
          <div>
            <div>
              RGB <h3>between 0-255</h3>
            </div>
            <div className={"input"}>
              <input
                type="number"
                placeholder="Red"
                name="Red"
                value={red}
                max="255"
                id="redValue"
                onChange={(e) => setRed(e.target.value)}
              />
              <input
                type="number"
                placeholder="Green"
                name="Green"
                value={green}
                max="255"
                id="greenValue"
                onChange={(e) => setGreen(e.target.value)}
              />
              <input
                type="number"
                placeholder="Blue"
                name="Blue"
                value={blue}
                max="255"
                id="blueValue"
                onChange={(e) => setBlue(e.target.value)}
              />
            </div>
          </div>
          <button className={"homeButton"} onClick={changeColor}>
            Click to Generate
          </button>
        </div>
        <History colors={colors} />
      </section>
    </div>
  );
}

Why does customElements.upgrade appear to not upgrade this custom element?

I have a situation similar to the example below: from a template element, I clone a node tree containing custom elements. One custom element is passed data during initialization, represented here by the line infobox.setData(getData()). The function I use to pass the data (setData) is added by my custom class, so I make sure the custom element is upgraded before calling it, by passing the node tree to customElements.upgrade. (I have also tried passing infobox itself.)

Unfortunately, when I try running my code or the example below I receive the error infobox.setData is not a function. I have confirmed infobox instanceof InfoBox is false and the element has no custom properties or methods prior to being connected to the document, so it seems customElements.upgrade is not upgrading the elements in the tree. What might be preventing it from doing so?

document.getElementById('addWidget').onclick = addWidget

class InfoBox extends HTMLElement {
  _data = ""

  connectedCallback() {
    this.render()
  }

  setData(val) {
    this._data = val
    this.render()
  }

  render() {
    if (!this?.isConnected) {
      return
    }

    this.replaceChildren(...this._data.split(' ').map(datum => {
      const el = document.createElement('span')
      el.innerText = datum
      return el
    }))
  }
}
customElements.define('info-box', InfoBox)

function addWidget() {
  const widget = document.getElementById('widgetTemplate').content.cloneNode(true)
  const infobox = widget.querySelector('info-box')

  customElements.upgrade(widget)

  console.assert(!(infobox instanceof InfoBox))
  console.assert(!('setData' in infobox))
  try {
    // TypeError: infobox.setData is not a function
    infobox.setData(getData())
  } catch {}

  document.getElementById('container').append(widget)

  // works because infobox was upgraded after being added to the document
  infobox.setData(getData())
}

function getData() {
  return ('lorem ipsum dolor sit amet consectetur adipiscing elit proin at ' +
    'vestibulum enim vestibulum ante ipsum primis in faucibus orci luctus')
}
#container {
  background: lightgrey;
  padding: 2em;
}

info-box {
  display: flex;
  flex-flow: row wrap;
  gap: .5em;
  padding: .5em;
  background: darkgrey;
}

info-box>span {
  background: lightblue;
  border-radius: .5em;
  padding: .5em;
}
<template id="widgetTemplate">
    <details>
        <info-box></info-box>
    </details>
</template>

<button id="addWidget">Add</button>
<div id="container"></div>

javascript function works only on firefox

I made a function that shows card images after I click a button. the problem is that it doesn’t work on chrome. the chrome editor presents an extra ‘/’ to the end of the path.

        function renderDeck(deck,ph)
    {
        
        var htmlStr = document.getElementById(ph).innerHTML;
        for (var i = 0; i < deck.length; i++) {
            htmlStr += '<div>';
            htmlStr += '<img src=' + deck[i].path + '/>';
            htmlStr += '</div>';
        }
        document.getElementById(ph).innerHTML = htmlStr;
    }

An example of what I push inside the deck

deck.push({ name: 'red_joker', path: 'cardImages/red_joker.png', val: 15 });

what can be the problem?

React Testing library queries can’t find last column in MUI’s Datagrid

I am trying to run some tests using React Testing Library/Jest to check if the edit and delete buttons that you can find in each row of the datagrid are working properly.

I am using the latest version of Material-UI‘s datagrid package. For each column, I have set flex and a minimum width so that the columns can grow as the window size grows but never be smaller than the minimum width.

I do not know the default window size that Jest uses for tests but for some reason, the last column “Actions” can’t be found by React Testing library queries. This means that you would probably have to scroll horizontally to see the last column.

I have disabled virtualization in the Datagrid component so that all rows and columns that are hidden should be visible. I have also tried setting global.innerWidth to a big value to see if all columns would be rendered. So far, nothing has worked.

Has anyone had the same issue or know what the solution would be for this issue?

Here is an image of how the Datagrid component looks:
Datagrid component

Here is the code of the component in question:

import { useCallback, useEffect, useRef, useState, useContext } from 'react';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { Box } from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import axios, { AxiosResponse } from 'axios';
import { useNavigate } from 'react-router-dom';

import TableTooltip from '../../components/Tooltip/Tooltip';
import { AppContext } from '../../context/provider';
import { ApiResult } from '../../api/ApiResultInterface';
import { ApiService } from '../../api/ApiSevice';
import { AlertActionTypes } from '../../context/alert/alert.action.types';
import DeleteItemModal from '../DeleteItemModal/DeleteItemModal';
import { classes, Root } from './ModelsTable.styles';

type Model = {
  id: string;
  companyName: string;
  modelName: string;
};

type Item = { company: string; id: string };

const ModelsTable = () => {
  const [models, setModels] = useState<Model[]>([]);
  const [open, setOpen] = useState(false);
  const [item, setItem] = useState<Item>({ company: '', id: '' });

  const navigate = useNavigate();
  const { dispatch } = useContext(AppContext);

  // Used to not update state if component is unmounted before data fetch is complete
  let _isMounted = useRef(true);

  const setAlert = useCallback(
    (msg: string, status: number) => {
      dispatch({
        type: AlertActionTypes.SetAlertMessage,
        payload: new ApiResult(msg, status),
      });
      dispatch({ type: AlertActionTypes.OpenAlertMessage, payload: true });
    },
    [dispatch]
  );

  const fetchModels = useCallback(async () => {
    try {
      const response: AxiosResponse<Model[]> = await ApiService.getAllModels();

      // Do nothing if component has unmounted while fetching data
      if (!_isMounted.current) {
        return;
      }

      setModels(response.data);
    } catch (err) {
      if (axios.isAxiosError(err) && err.response) {
        const status = err.response.status;
        const error = err.response.data;

        setAlert(error.message, status);
      } else if (err instanceof Error) {
        setAlert(err.message, 400);
      }
    }
  }, [setAlert]);

  const deleteModel = async (company: string, id: string) => {
    try {
      let deletionResponse: AxiosResponse<{
        message: string;
      }> = await ApiService.deleteModel(company, id);
      const modelsResponse: AxiosResponse<Model[]> =
        await ApiService.getAllModels();

      // Do nothing if component has unmounted while fetching data
      if (!_isMounted.current) {
        return;
      }

      setModels(modelsResponse.data);
      setAlert(deletionResponse.data.message, deletionResponse.status);
    } catch (err) {
      if (axios.isAxiosError(err) && err.response) {
        const status = err.response.status;
        const error = err.response.data;

        setAlert(error.message, status);
      } else if (err instanceof Error) {
        setAlert(err.message, 400);
      }
    }
  };

  useEffect(() => {
    return () => {
      _isMounted.current = false;
    };
  }, []);

  useEffect(() => {
    fetchModels();
  }, [fetchModels]);

  // Table columns
  const columns: GridColDef[] = [
    {
      field: 'id',
      headerName: 'Id',
      description: 'Id',
      headerAlign: 'center',
      align: 'center',
      minWidth: 100,
      flex: 2,
      renderCell: (cellParams) => {
        const value = cellParams.value ? (cellParams.value as string) : '';

        return (
          <TableTooltip title={value}>
            <div className={classes.cellText}>{cellParams.value}</div>
          </TableTooltip>
        );
      },
      renderHeader: (headerParams) => {
        return (
          <TableTooltip title={headerParams.colDef.description as string}>
            <div className={classes.cellText}>
              {headerParams.colDef.description}
            </div>
          </TableTooltip>
        );
      },
    },
    {
      field: 'modelName',
      description: 'Model',
      headerName: 'Model',
      headerAlign: 'center',
      align: 'center',
      minWidth: 100,
      flex: 2,
      renderCell: (cellParams) => {
        const value = cellParams.value ? (cellParams.value as string) : '';

        return (
          <TableTooltip title={value}>
            <div className={classes.cellText}>{cellParams.value}</div>
          </TableTooltip>
        );
      },
      renderHeader: (headerParams) => {
        return (
          <TableTooltip title={headerParams.colDef.description as string}>
            <div className={classes.cellText}>
              {headerParams.colDef.description}
            </div>
          </TableTooltip>
        );
      },
    },
    {
      field: 'companyName',
      description: 'Company',
      headerName: 'Company',
      headerAlign: 'center',
      align: 'center',
      minWidth: 100,
      flex: 2,
      renderCell: (cellParams) => {
        const value = cellParams.value ? (cellParams.value as string) : '';

        return (
          <TableTooltip title={value}>
            <div className={classes.cellText}>{cellParams.value}</div>
          </TableTooltip>
        );
      },
      renderHeader: (headerParams) => {
        return (
          <TableTooltip title={headerParams.colDef.description as string}>
            <div className={classes.cellText}>
              {headerParams.colDef.description}
            </div>
          </TableTooltip>
        );
      },
    },
    {
      field: 'actions',
      description: 'Actions',
      headerClassName: 'last-column-header',
      headerName: 'Actions',
      headerAlign: 'center',
      align: 'center',
      hideSortIcons: true,
      disableColumnMenu: true,
      minWidth: 100,
      flex: 1,
      renderCell: (cellParams) => {
        // Get model's id and company from the other columns of the row
        const id = cellParams.getValue(cellParams.id, 'id')?.toString() || '';
        const company =
          cellParams.getValue(cellParams.id, 'companyName')?.toString() || '';

        return (
          <div className={classes.statusCell}>
            <div className={classes.statusContainer}>
              <EditIcon
                className={classes.editButton}
                onClick={() =>
                  navigate(`/dashboard/update-model/${company}/${id}`)
                }
              />
              <DeleteOutlineIcon
                className={classes.deleteButton}
                color="secondary"
                onClick={() => {
                  setItem({ company, id });
                  setOpen(true);
                }}
              />
            </div>
          </div>
        );
      },
      renderHeader: (headerParams) => {
        return (
          <TableTooltip title={headerParams.colDef.description as string}>
            <div className={classes.cellText}>
              {headerParams.colDef.description}
            </div>
          </TableTooltip>
        );
      },
    },
  ];

  return (
    <Root>
      <h1 className={classes.tableTitle}>Models</h1>
      <Box boxShadow={3} className={classes.modelsTableContainer}>
        <DataGrid
          rows={models}
          loading={models.length === 0}
          columns={columns}
          className={classes.modelsTable}
          checkboxSelection={false}
        />
      </Box>
      <DeleteItemModal
        open={open}
        item={item}
        setOpen={setOpen}
        setItem={setItem}
        deleteItem={deleteModel}
      />
    </Root>
  );
};

export default ModelsTable;

Array index not working in tampermonkey script

I’m working on a little tampermonkey script, to do some clicking automation for a little game.

The way it should work is the following:
In the game, there are cars. You can click on each of these cars and then press “Start Race” to start a race and afterwards, you need to click on a button that says “see results” and then “claim rewards”. The hole script works – but only one time for one car..

Personally I have multiple cars and for each car, you can do 12 races. So what I’d like the script to do, is to go through each car, race it and do that 12 times..

You can see the logic with the timeouts, which work fine (although this might not be practice – they work, as the console.log outputs are there at the right timings).

The only problem I have right now is clicking on the right car. I tried various debuggings, but it just doesn’t want to work. It races with one car only (strange here: the LAST car, not the first) and then it doesn’t do anything anymore, except logging (can’t do anything, if it doesn’t click the car). So it always only does the race with one car, and then doesn’t click any car anymore.. In debugging, you can clearly see, that array is built up correctly though:

enter image description here

Does anybody have an idea what I’m doing wrong? I’ve been sitting here for hours, trying to find the problem…

// ==UserScript==
// @name         AutoPlay Script
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Automatically play
// @author       You
// @match        https://myplayingpage.de
// @icon         https://www.google.com/s2/favicons?domain=https://myplayingpage.de
// @grant        none
// @require      http://code.jquery.com/jquery-3.4.1.min.js
// ==/UserScript==

(function() {
    'use strict';

    var carsArray = [];
    var carArrayIndex = 0;
    var timeoutTimer = 0; 
    setTimeout(function(){ 
        for(var i = 0; i<12; i++){
            carArrayIndex = 0;
            $('.car-list .item.content').each(function(){  
                carsArray[carArrayIndex] = $(this);
                debugger;
                setTimeout(function(){
                    carsArray[carArrayIndex].click(); 
                    console.log("car click");
                },2000+timeoutTimer);
                setTimeout(function(){ //warte 1 Sekunde
                    $('.custom-btn.btn-green').click(); 
                    console.log("start race");
                },5000+timeoutTimer);
                setTimeout(function(){ //warte 14 Sekunden
                    $('.custom-btn.btn-yellow').click(); 
                    console.log("result click");
                },21000+timeoutTimer);
                setTimeout(function(){ 
                    $('.ant-btn.ant-btn-success, .ant-btn.btn-green').click(); 
                    console.log("rewards claim click");
                },27000+timeoutTimer);
                timeoutTimer+=30000;
                carArrayIndex++;
            });
        }
    },5000);

})();

Cordova [iOS] – DeviceReady not firing (working fine on [android])

I’ve been building an application for Android, which works perfectly. Now I’m trying to add an iOS platform. Migrated my application on my Macbook, and run the application on an iPhone 8.

If I create a new project, the Cordova startup app works without issue.

Splash screen opens, then nothing happens. If I put <preference name="AutoHideSplashScreen"/> value to true, then splash screen comes, then hides, leaving a blank white screen. It looks like DeviceReady isn’t firing for some reason

index.js

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    alert('IOS Device Ready');
    navigator.splashscreen.hide();
}

Config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.template" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>Template</name>
    <description>
        Template
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Template
    </author>
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="*"/>
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="Orientation" value="landscape" />
    <preference name="Fullscreen" value="true" />
    <preference name="BackgroundColor" value="#FFFFFFFF"/>
    <preference name="SplashScreen" value="screen" />
    <preference name="AutoHideSplashScreen" value="false" />
    <preference name="SplashScreenDelay" value="1000" />
    <preference name="FadeSplashScreen" value="false" />
    <preference name="ShowSplashScreenSpinner" value="false" />
    <preference name="AllowInlineMediaPlayback" value="true" />
    <preference name="DisallowOverscroll" value="true" />

    <platform name="android">
        <allow-intent href="market:*" />
        <resource-file src="www/audio/zombie.wav" target="app/src/main/res/raw/zombie.wav" />
        <preference name="android-manifest/application/activity/@android:theme" value="@android:style/Theme.Light.NoTitleBar.Fullscreen"/>
        <preference name="AndroidXEnabled" value="true" />
        <preference name="android-minSdkVersion" value="23" />
        <preference name="AndroidBlacklistSecureSocketProtocols" value="SSLv3,TLSv1" />
        
        <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application/activity">
            <activity android:theme="@style/MyFullTheme"/>
        </edit-config>
        <edit-config file="strings.xml" mode="add" target="/resources">
            <style name="MyFullTheme" parent="@style/Theme.AppCompat.NoActionBar">
                <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item><!-- Use 100% screen size even on borderless device / notch device -->
                <item name="android:windowTranslucentStatus">true</item>
                <item name="android:windowTranslucentNavigation">true</item>
                <item name="android:windowFullscreen">true</item><!-- Use 100% screen size -->
                <item name="android:windowActionBar">false</item>
                <item name="android:windowNoTitle">true</item>
                <item name="android:windowContentOverlay">@null</item>
                <item name="android:windowBackground">@android:color/white</item>
                <item name="android:statusBarColor">@android:color/black</item>
            </style>
        </edit-config>
    </platform>
    
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <splash src="res/screen/ios/Default@2x~universal~anyany.png" />
        
        <preference name="AllowNewWindows" value="true" />
        <preference name="MediaPlaybackAllowsAirPlay" value="true" />
        <preference name="Allow3DTouchLinkPreview" value="false" />
        <preference name="AllowBackForwardNavigationGestures" value="false" />
        <preference name="ShowSplashScreen" value="false" />
        
        <preference name="WKWebViewOnly" value="true" />

        <feature name="CDVWKWebViewEngine">
            <param name="ios-package" value="CDVWKWebViewEngine" />
        </feature>

        <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
    </platform>
    
    <platform name="browser">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

usage of radio button for asp server in javascript

I have this code for asp server in javascript. I need to add an IF condition at the end so that it adds in the responce a “mr.” if they check the male gender radio button and “miss.” if check female radio button. Right in front of the name they submit. It seems pretty simple but i cant find the right syntax for it.

<%@ LANGUAGE="Javascript" %>
<HTML>
    <HEAD>
        <META NAME="GENERATOR" Content="Microsoft FrontPage 4.0">
        <meta http-equiv="Content-Type" content="text/html; charset=utf8">
        <TITLE>Main Page</TITLE>
    </HEAD>

    <BODY TopMargin="0" Leftmargin="0">
        <form action="./ask.asp" method="post">
            Student name: <input type="text" name="name" size="20"><br><br>

            Sex:
            <input type="radio" name="choice" value="Male" id="choice-Male">
            <label for="choice-Male">Male</label><br>

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

            <input type="radio" name="choice" value="Female" id="choice-Female">
            <label for="choice-Female">Female</label><br><br>       
            
            <input type="submit" value="Submit Form"><br>
        </form>

        <%
            Response.Write("Thanks " + Request.Form("name"))
        %>      
    </BODY>
</HTML>

How to check if input is a real character when a keyboard event is triggered in JavaScript/TypeScript?

I registered a keyboard listener in JS for my image gallery view. When the user inputs a character I want to jump to the first item whose name matches the first character of the typed character.

I can of course just check for [a-zA-Z0-9-_…] but there are many other characters that the user could type, e.g. through a Japanese or Chinese keyboard.

Is there a way to test if an input is a real text character?

EventHandler is not working.It gives No output when I click the button

var urlId = 'https://www.themealdb.com/api/json/v1/1/lookup.php?i='; //search by id
const mealList = document.getElementById('list-Items-container');
var input = document.getElementById('inputText');
const mealListFavorites = document.getElementById(
  'list-Items-container-favorites'
);

window.onload = renderFavorites;

document.querySelector('form').addEventListener('submit', handleSubmitForm);

// .getElementById('get-details')
mealList.addEventListener('click', handleGetDetailsOrAddToFavorites);
mealListFavorites.addEventListener('click', handleRemoveFavorites);

function handleRemoveFavorites(e) {
  e.preventDefault();
  console.log(e.target.value);
}

function handleGetDetailsOrAddToFavorites(e) {
  e.preventDefault();
  console.log('clicked');
  if (e.target.value == 'details') {
    let mealItem = e.target.parentElement.parentElement;

    fetch(
      `https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
    )
      .then(function (res) {
        return res.json();
      })
      .then((data) => {
        mealRecipeModal(data.meals);
      });
  } else if (e.target.value == 'favour') {
    let mealItem = e.target.parentElement.parentElement;

    fetch(
      `https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
    )
      .then(function (res) {
        return res.json();
      })
      .then((data) => {
        window.localStorage.setItem(
          mealItem.dataset.id,
          JSON.stringify(data.meals)
        );
      });
  }

  console.log(Object.entries(localStorage));
}

function mealRecipeModal(meal) {
  console.log(meal[0]);
  const destination = meal[0].strSource;
  console.log(destination);
  window.open(`${meal[0].strSource}`);
}

function handleSubmitForm(e) {
  e.preventDefault();

  let input = document.querySelector('input');

  findFood(url + input.value);
  input.value = '';
}

function findFood(address) {
  fetch(address)
    .then(function (res) {
      //console.log(res);
      return res.json();
    })
    .then((data) => {
      console.log(data);

      let html = '';
      if (data.meals) {
        data.meals.forEach((meal) => {
          html += `<div class="food-card" data-id="${meal.idMeal}">
          <div class="food-card-image">
              <img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
              </div>
              <div class="food-card-info">
                  <h3>${meal.strMeal}</h3>
                  </div>
                  <div class="food-card-features">
                  <button id="favorites" value="favour">Add</button>
                  <button id="get-details" value="details" >Details</button>
                  </div>
              </div>`;
        });
      }
      console.log(html);
      mealList.innerHTML = html;
    });
}
var html1 = '';
function findFoodFavorite(address) {
  fetch(address)
    .then(function (res) {
      //console.log(res);
      return res.json();
    })
    .then((data) => {
      console.log(data);

      if (data.meals) {
        data.meals.forEach((meal) => {
          html1 += `<div class="food-card" data-id="${meal.idMeal}">
          <div class="food-card-image">
              <img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
              </div>
              <div class="food-card-info">
                  <h3>${meal.strMeal}</h3>
                  </div>
                  <div class="food-card-features">
                  <button id="favorites" value="defavour" >Remove</button>
                  <button id="get-details" value="details" >Details</button>
                  </div>
              </div>`;
        });
      }
      console.log(html1);
      mealListFavorites.innerHTML = html1;
    });
}
function renderFavorites() {
  const urlArray = [];
  console.log(Object.entries(localStorage));
  for (var i = 0; i < localStorage.length; i++) {
    console.log(Object.entries(localStorage)[i][0]);
    urlArray.push(Object.entries(localStorage)[i][0]);
  }
  console.log(urlArray);
  urlArray.forEach((id) => findFoodFavorite(urlId + id));
}

I am using API for my website.My handleGetDetailsOrAddToFavorites event handler is working but handleRemoveFavorites EventHandler which has been implemented the same way is not working.But why???It gives no Error.Also console.log(e.target.value) in handleRemoveFavorites console logs Nothing.I want my handleRemoveFavorites to give out (e.target.value) so that i can fetch indivisual items Id and delete them from localstorage.
Please Help.

passing data in nested function

i’m a beginner in javascript and i tried to learn about function that called inside a function which redefine a value of a variable. Here’s the code

var a;

function app2(a) {
  var a = 8;
  return a
}

function app(a) {
  var a = 7;
  app2(a)
  return a
}
console.log(app(a));

when i run code, it still show 7 as the output. i thought it will be 8 because i’ve called the function app2 in the app function. why the value doesn’t change into 8? and what should i do update the variable value inside the nested function? thanks in advance

How to force one async to be called after the other?

In this code, I am first deleting a collection and then inserting data into it. But I realised that the insertMany is called halfway of the deleteMany so the data is all messed up. How do I force insertMany to be called after deleteMany fully does its job?

    return new Promise(async (resolve, reject) => {
        try {
            try {
                //delete old data
                await Rewards.deleteMany({});
                //post the data into the Rewards schema here
                let query = await Rewards.insertMany(data);
                resolve(query);
            } catch (e) {
                console.log("e", e);
            }

        } catch (e) {
            reject(e);
        }
    })
}```

how can I know if submit post method was success in html

I have a form in html with a post method
I need to know when the response to the post request
how can I catch it?

<form action='MyUrl' method="post" onsubmit="sub()">
     <input type="text" name="fname" required oninvalid="this.setCustomValidity('first name is required')"
                oninput="this.setCustomValidity('')">
     <button type="submit" name = "submit" value = "Submit">send</button>
</form>