How to handle non-bundled code on runtime using webpack?

I have a web application made purely in jquery. I have properly configured webpack and everything is working as expected, like minification, code splitting, etc.

The problem is, when the app runs on browser, a custom js file is loaded from database and executed when the DOM is rendered. This js file has dependency on the already bundled code modules/functions.

Example:

// user.js | From static codebase
import { GetFullName } from './common'; // From static codebase

const user = {};
user.Login = () => {}

export default user;

Now the custom code will have a content like this:

$('#login').click(user.Login) // References "user" module from the main code.
// This will throw a reference error saying user is not defined. 

Note: We have recently introduced import/export in the codebase due to webpack’s lazy loading and stuffs. Otherwise the references were by default global.
“user” was globally accessible for the case of the example above.

Webpack is supposed to generate the dependency graph from the static files that were provided while compiling and thus function and variable names will be different everytime.

The custom js file will throw errors due to missing dependencies.

Is there a way to resolve this problem?

I tried to create global references of the modules in the main bundle and make them accessible. However this doesn’t seem the right way and would greatly impact lazy loading of modules.

Ternary operator array sort check. Having trouble understanding what does it to

Can you guys help me understand how does this code check if inputed array sorted by ascending, descending or not sorted at all? I tried to understand it myself for two days but with no success

Here is the code

const arraySortInfo = (inputArray) => {
  if (inputArray.some((element) => typeof element !== "number")) {
    return "Some elements are not numbers";
  }

  if (
    inputArray.every((element, index) =>
      index > 0 ? element >= inputArray[index - 1] : true
    )
  ) {
    return "Array sorted by ascending";
  }

  if (
    inputArray.every((element, index) =>
      index > 0 ? element <= inputArray[index - 1] : true
    )
  ) {
    return "Array sorted by descending";
  }

  return "Array isn't sorted";
};

const a = [5, "abc", 10, 1];
const b = [4, 10, 14, 25, 25, 50];
const c = [150, 132, 80, 40];
const d = [15, 26, 10, 23, 85];

I specifically lost in this lines of code and the same one for descending

if (
    inputArray.every((element, index) =>
      index > 0 ? element >= inputArray[index - 1] : true
    )
  ) {
    return "Array sorted by ascending";
  }

I tried to sit and write down everything on paper but so far I thought that I understood what it does with ascending, but then I tried to figure out descending check the same way and it didn’t add up so I must be wrong at something.

Here is how I understand it on ascending example

inputArray[4, 7, 10 for example].every((element, index) =>
 first time     index 0 > 0 ? element 4 >= inputArray*//4,7,10 = 2 indexes//*[index */0/* - 1] : true
 *so if 4 >= 1 it return true*
 second time    index > 0 ? element 7  >= inputArray*//4,7,10 = 2 indexes//*[index */1/* - 1] : true
 *if 7 >= 2 returns true*
 third time     index > 0 ? element 10 >= inputArray*//4,7,10 = 2 indexes//*[index */2/* - 1] : true
 *if 10 >= 1 return true*
*and if every time this was true it will return "Array sorted by ascending"*

It worked here for me. But it didn’t work the same way for descending numbers so I must be wrong. Maybe I’m wrong about (element, index) inputs?

How can i display the data button in the table that i created using JavaScript?

I’m trying to create a table that displays the selected data from the json file. With the coordinates data selected from the json file, i need to make the coodinates data into a button so i can setZoom() to the map when the corresponded coordinated is clicked. I am able to make the button work when is not in the table. but now i am struggling to make it work in the table. I have no idea how to make it work. Please help me it will be a very big help to me. Thanks :slight_smile:

here is my html code:

<div class="col-12 form-group mt-5">
      <div class="card" style="box-shadow: 0 0 8px rgb(0, 0, 0, 0.3)">
        <h6 class="text-muted text-center p-3 mt-2">Map</h6>
        <div class="card-body">
          <div id="googleMap" style="width: 100%; height: 400px"></div>
        </div>
      </div>
    </div>
    <div id="numbers" class="data_btn"></div>

    <div class="container">
      <div class="table-responsive">
        <table class="table table-bordered table-stripped" id="events_table">
          <thead>
            <tr>
              <th>ROBOT ID</th>
              <th>ps</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>

here is my js code

 <script>
      function myMap() {
        var mapProp = {
          position: new google.maps.LatLng(32.735316, -117.149046),
          zoom: 1,
        };
        var map = new google.maps.Map(
          document.getElementById("googleMap"),
          mapProp
        );
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY=myMap"></script>
<script>
      $.getJSON("example.json", function (data) {
        const map = new google.maps.Map(document.getElementById("googleMap"), {
          zoom: 5,
          center: new google.maps.LatLng(
            1.5298600000000002,
            110.36003000000001
          ),
          mapTypeId: google.maps.MapTypeId.ROADMAP,
        });
        var output = "";
        const { tracks } = data;
        $.each(tracks, function (key, value) {
          const NewlatLngStr = value.ps.split(",");
          const results = document.getElementById("numbers");
          function ZoomAndCenter(NewlatLngStr) {
            map.setCenter(
              new google.maps.LatLng(NewlatLngStr[0], NewlatLngStr[1])
            );
            map.setZoom(20);
          }
          const btn = document.createElement("button");
          const Questions = NewlatLngStr;
          btn.textContent = NewlatLngStr;
          btn.addEventListener("click", () => ZoomAndCenter(Questions));
          results.appendChild(btn);
          console.log(btn);
          output += "<tbody>";
          output += "<tr>";
          output += "<td>" + value.Robotid + "</td>";    
          output += "<td>" + btn + "</td>";
          output += "</tr>";
          output += "</tbody>";
        });
        $("#events_table").html(output);
      });
    </script>

here is how my json file data look like

{
  "result": 0,
  "location": {
    "walk": null
  },
  "tracks": [
    { "Robotid": "123456789", "ps": "1.5298600000000002,110.36003000000001" },
    { "Robotid": "123456789", "ps": "1.52872, 110.36453" },
    { "Robotid": "123456789", "ps": "1.5278, 110.36775000000002" },
    { "Robotid": "123456789", "ps": "1.5273500000000002, 110.37160000000002" }
  ]
}

my countdown timer is not working fine everytime in react

This is a game that I am building and in this game I have created some levels. But when the game ends for the first time the second time my countdown timer is not getting decremented.

this is my App.js component:

import "./App.css";
import React, { useState, useEffect, useCallback } from "react";
import SingleCard from "./components/singleCard/SingleCard";
import Timer from "./components/timer/Timer";
import Modal from "./components/modal/Modal";
import soundOn from "./images/soundon.png";
import soundOff from "./images/soundoff.png";
import { Helmet } from "react-helmet";

const cardImages = [
  { src: "/img/img-1.png", matched: false },
  { src: "/img/img-2.png", matched: false },
  { src: "/img/img-3.png", matched: false },
  { src: "/img/img-4.png", matched: false },
  { src: "/img/img-5.png", matched: false },
  { src: "/img/img-6.png", matched: false },
];

function App({ background, wrongAns, correctAns, deadSound, winSound }) {
  const [cards, setCards] = useState([]);
  const [turns, setTurns] = useState(0);
  const [choiceOne, setChoiceOne] = useState(null);
  const [choiceTwo, setChoiceTwo] = useState(null);
  const [disabled, setDisabled] = useState(false);
  const [isgameEnd, setGameEnd] = useState(false);
  const [timerStart, setTimerStart] = useState(false);
  const [playSound, setPlaySound] = useState(false);
  const [count, setCount] = useState(0);
  const [IsPlaying, setIsPlaying] = useState(true);
  const [isModalOpen, setModalIsOpen] = useState(false);
  const [restartTimer, setRestartTimer] = useState(false);
  const [isMute, setMute] = useState(false);
  const [loading, setLoading] = useState(true);

  function handleMute(state = false) {
    background.muted = state;
    wrongAns.muted = state;
    correctAns.muted = state;
    deadSound.muted = state;
    winSound.muted = state;
    setMute(state);
  }

  let timer;

  // function that will decide the condition for opening the modal

  const toggleModal = () => {
    setModalIsOpen(true);
  };

  //  function that will execute when we click a button in the modal

  const handlePlaySound = () => {
    setPlaySound(false);
  };

  //  function that will execute when game is set to background in android
  function AudioBgOnPause() {
    if (playSound === true) {
      background.pause();
      setIsPlaying(false);
    }
  }
  // functiona that will execute when game is again resumed
  function AudioBgOnResume() {
    if (IsPlaying === false) {
      setIsPlaying(true);
    }
  }
  //  creating there global reference so that we can call these functions in the index file
  window.AudioBgOnPause = AudioBgOnPause;
  window.AudioBgOnResume = AudioBgOnResume;
  //  check if playSound is off or on

  if (playSound === false) {
    background.pause();
  } else if (playSound === true && IsPlaying === true) {
    background.play();
  }

  //  Play Again

  const playAgain = () => {
    // setCards([]);
    shuffleCards();
    setTurns(0);
    setChoiceOne(null);
    setChoiceTwo(null);
    setDisabled(false);
    setGameEnd(false);
    setTimerStart(false);
    setPlaySound(false);
    setCount(0);
    setIsPlaying(true);
    setModalIsOpen(false);
    setRestartTimer(true);
    setMute(false);
  };
  const restartGame = () => {
    playAgain();
  };
  //  check if isGameEnd is true i.e. the game is ended
  //  losing condition
  useEffect(() => {
    if (turns < 6 && isgameEnd === true) {
      setDisabled(true);
      setTimerStart(false);
      clearInterval(timer);
      if (playSound === true) {
        deadSound.play();
      }
      setPlaySound(false);
      setTimeout(() => {
        toggleModal();
      }, 2000);
    }
  }, [turns, isgameEnd]);

  //  winning situation
  useEffect(() => {
    if (
      (turns === 6 && isgameEnd === false) ||
      (turns === 6 && isgameEnd === true)
    ) {
      // clearInterval(timer);
      // setDisabled(true);
      setRestartTimer(true);
      setTimerStart(false);
      if (playSound === true) {
        winSound.play();
      }
      setPlaySound(playSound);
      shuffleCards();
      // setTimeout(() => {
      //   toggleModal();
      // }, 2000);
    }
  }, [turns, isgameEnd]);

  //  shuffle Cards

  const shuffleCards = () => {
    const shuffleCards = [...cardImages, ...cardImages]
      .sort(() => Math.random() - 0.5)
      .map((card) => ({ ...card, id: Math.random() }));
    setCards(shuffleCards);
    setTurns(0);
  };
  // console.log("cards array", cards);
  //  handle a choice
  const handleChoice = (card) => {
    setTimerStart(true);
    // background.play();
    background.loop = true;
    //  checking if the counter is one only then set sound to true when the card is flipped for first time
    count === 1 ? setPlaySound(true) : setPlaySound(playSound);
    //  after that increment the counter so that the upper condition should not hold anymore
    setCount(count + 1);
    choiceOne ? setChoiceTwo(card) : setChoiceOne(card);
  };

  //  compare 2 selected cards
  useEffect(() => {
    if (choiceOne && choiceTwo) {
      setDisabled(true);
      if (choiceOne.src === choiceTwo.src) {
        setCards((prevCards) => {
          return prevCards.map((card) => {
            if (card.src === choiceOne.src) {
              return { ...card, matched: true };
            } else {
              return card;
            }
          });
        });
        if (playSound === true) {
          correctAns.play();
        }
        setTurns((prevTurns) => prevTurns + 1);
        resetTurn();
      } else {
        if (playSound === true) {
          wrongAns.play();
        }
        setTimeout(() => resetTurn(), 500);
      }
    }
  }, [choiceOne, choiceTwo]);

  //  start a new game automatically
  //  set counter to one when the component first mounts so that sound starts to play on first click only
  useEffect(() => {
    shuffleCards();
    setCount(count + 1);
  }, []);

  // reset choices
  const resetTurn = () => {
    setChoiceOne(null);
    setChoiceTwo(null);
    setDisabled(false);
  };
  // console.log("restart App", restartTimer);
  //  timer callback
  const onGameEnd = useCallback(() => {
    setGameEnd(!isgameEnd);
  }, [isgameEnd]);

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 4000);
  }, []);

  return (
    <>
      <Helmet>
        <meta charSet="utf-8" />
        <title>Match Maker</title>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
        />
      </Helmet>
      <div className="App">
        {loading && (
          <div className="loader-container">
            <div className="spinner"></div>
          </div>
        )}
        <>
          {/* <img
              className="logo"
              src="https://cheetay.pk/static/images/newLandingPage/logo.svg"

              alt="card back"
            /> */}
          <div
            style={
              loading ? { visibility: "hidden" } : { visibility: "inherit" }
            }
          >
            <div className="soundBtn">
              {!isMute === true ? (
                <div
                  className="soundIcon"
                  style={{
                    cursor: "pointer",
                    khtmlUserSelect: "none",
                    MozUserSelect: "none",
                    OUserSelect: "none",
                    userSelect: "none",
                  }}
                  onClick={() => handleMute(!isMute)}
                >
                  <img src={soundOn} alt="soundOff" />
                </div>
              ) : (
                <div
                  className="soundIcon"
                  style={{
                    cursor: "pointer",
                    khtmlUserSelect: "none",
                    MozUserSelect: "none",
                    OUserSelect: "none",
                    userSelect: "none",
                  }}
                  onClick={() => handleMute(!isMute)}
                >
                  <img src={soundOff} alt="soundOff" />
                </div>
              )}
            </div>
            <div className="card-grid">
              {cards.map((card) => (
                <SingleCard
                  key={card.id}
                  card={card}
                  handleChoice={handleChoice}
                  flipped={
                    card === choiceOne || card === choiceTwo || card.matched
                  }
                  disabled={disabled}
                  isModalOpen={isModalOpen}
                />
              ))}
            </div>
            <div className="TimerAndTurnsInfo">
              <Timer
                timerStart={timerStart}
                timer={timer}
                onGameEnd={onGameEnd}
                restartTimer={restartTimer}
              />
              <p>matched {turns}</p>
            </div>
          </div>
        </>
      </div>
      {isModalOpen && (
        <Modal handlePlaySound={handlePlaySound} restartGame={restartGame} />
      )}
    </>
  );
}

export default App;

and this is my timer component:

import React, { useEffect, useState } from "react";
import "./Timer.css";
const Child = ({ timerStart, timer, onGameEnd, restartTimer }) => {
  const [seconds, setSeconds] = useState(40);
  // let time = 40;
  useEffect(() => {
    if (restartTimer === true) {
      setSeconds(40);
    }
  }, [seconds, restartTimer]);
  // console.log("restart Timer", restartTimer);
  useEffect(() => {
    if (timerStart === true) {
      timer = setInterval(() => {
        if (seconds > 0) {
          setSeconds(seconds - 1);
        }
        if (seconds === 0) {
          onGameEnd(true);
          clearInterval(timer);
        }
      }, 1000);
    }
    return () => clearInterval(timer);
  });

  return (
    <p className="time">
      Time{" "}
      <span className="span1">
        <span>{seconds}s</span>
      </span>
    </p>
  );
};

const Timer = React.memo(({ timerStart, timer, onGameEnd, restartTimer }) => (
  <Child
    timerStart={timerStart}
    timer={timer}
    onGameEnd={onGameEnd}
    restartTimer={restartTimer}
  />
));

export default Timer;

my timer gets re initialized when restartTimer state is set to true.

Infinitely posting data to server problem with using fetch POST in JavaScript

I am a university student and this is my first time of putting all together of server, api and client sides.

My problem is that first I have created an API using Django-Rest framework.
When I post data to that server using fetch function in JavaScript, it keeps posting that data and does not stop until I close. In the server database, many same data have been created.

I cannot figure out how to fix it. My intention was I want to post the data just once.
Please help me how to do it.

Thank you.

how to generate vanilla Javascript from given html code automatically

i want

user pest html code in textarea and then php script print the Javascript that can be used for generating same html code using Javascript

i have done the getting tag name, create tag code, ‘adding class, attributes’ but i unable write “appendChild” like code because i can’t find which is parent element & which if child element of which element

i have write following code

<html>
<style>
    .ac{
        color:red;
    }
</style>
<body>
    <form action="" method="post">
        <textarea name="data" id="code" cols="200" rows="20">
<?php 
    if(isset($_POST['data']))
    {
           echo $_POST['data']; 
    }
?>
</textarea>
        <input type="submit">
    </form>
</body>

</html>

<?php

    
    if(isset($_POST['data']))
    {
        echo "<div id=tag0>";
        echo $_POST['data'] ;
        echo "</div>";
    }

?>

<?php

    if(isset($_POST['data']))
    {
        //divide start tag and end tag
        $array=str_split($_POST['data']);
        $tag=array();
        $i=0;
        $tag_close=false;
        $tag_star=false;

        foreach($array as $key => $value)
        {
            // echo "<hr>" .$i." is value of i<hr>";
            // echo $tag_close . $tag_star;

            //<html></html>

            // if($value=' ')
            // {
                
            // }
            // else
             if($value == '>')
            {
                $tag_close=true;
                $tag_star=false;
                $i++;

            }
            else if($value == '<')
            {
                $tag_star=true;
            }
            else if($tag_star)
            {
                
                $tag_close=false;

                if(!isset($tag[$i]))
                {
                    $tag[$i]='';
                }
                $tag[$i]=$tag[$i].$value;
 
            }
            
             
            
        }
//writing javascript
        $k=1;
        $tag_name='';
        $end_tag_started=false;
        $attribut=array();
        $attribut_val=array();
        $j=0;
        $o=0;
        $attribut_value_started=false;
// one y one tag adding and it's attriut
        foreach($tag as $key => $value)
        {
            $t='tag'.$k;
            $p='tag'.$o;
            $value_aaray=str_split($value);
            $tag_name='';
            $attribut=array();
            $attribut_val=array();
            $j=0;

            foreach($value_aaray as $val)
            {
                
                if($val==' ')
                {
                    $attribut[$j]='';
                    $attribut_val[$j]='';
                    foreach($value_aaray as $val_array)
                    {
                        if($val_array == " ")
                        {
                            $j++;
                            $attribut_value_started=false;
                        }
                        else if($val_array == "=")
                        {
                            $attribut_value_started=true;
                        }
                        else
                        {
                            if($attribut_value_started)
                            {
                                @$attribut_val[$j]=$attribut_val[$j].$val_array;
                            }
                            else
                            {
                                @$attribut[$j]=$attribut[$j].$val_array;
                            }
                        }
                    }

                    break;
                }
                if($val == '/')
                {
                    $end_tag_started=true;
                    break;            
                }

                $tag_name=$tag_name.$val;
            }

            if(! $end_tag_started)
            {
                echo "<br> t";

                echo $t ."= document.createElement("".$tag_name."");";
                echo "<br> t";

                for($l=1;$l<count($attribut);$l++)
                {
                    echo " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $t.setAttribute("".@$attribut[$l]."","".@$attribut_val[$l]."");<br>";
                }

            }

            $end_tag_started=false;
            $k++;
        }


        echo "<hr>'tag'";
        print_r($tag);
        echo "<hr> ' letter array ' ";
        print_r($array);

        // for appendChild code but not working
        $a=array();
        for($i=0;$i<(count($tag));$i++)
        {
            $val=str_split($tag[$i]);

                if($val[0]=="/")
                {
                    echo "<hr>";
                    echo $a[]=" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; tag". ( $i-2 ) .".appendChild(tag". ($i-1).");";
                }
        }

    }

?>

i get following output

textarea is start


<div>

<div>
</div>

<div>

<div>
</div>

</div>

</div>
 
textarea is end


tag1= document.createElement("div");

tag2= document.createElement("div");

tag4= document.createElement("div");

tag5= document.createElement("div");
'tag'Array ( [0] => div [1] => div [2] => /div [3] => div [4] => div [5] => /div [6] => /div [7] => /div )
' letter array ' Array ( [0] => < [1] => d [2] => i [3] => v [4] => > [5] => [6] => [7] => [8] => [9] => < [10] => d [11] => i [12] => v [13] => > [14] => [15] => [16] => < [17] => / [18] => d [19] => i [20] => v [21] => > [22] => [23] => [24] => [25] => [26] => < [27] => d [28] => i [29] => v [30] => > [31] => [32] => [33] => [34] => [35] => < [36] => d [37] => i [38] => v [39] => > [40] => [41] => [42] => < [43] => / [44] => d [45] => i [46] => v [47] => > [48] => [49] => [50] => [51] => [52] => < [53] => / [54] => d [55] => i [56] => v [57] => > [58] => [59] => [60] => [61] => [62] => < [63] => / [64] => d [65] => i [66] => v [67] => > )
            tag0.appendChild(tag1);
            tag3.appendChild(tag4);
            tag4.appendChild(tag5);
            tag5.appendChild(tag6);

About assigning object

im facing an issue while saving objects in objects

i have data that looks alike

 {
      
        "channel": "Domain",
        "config": {
            "countryCode": "91",
            "FieldOperationCompletedEvent": {
                "attrs": {
                    "ProductOrderId": "$.event.userTask"
                }
            }
        }
    } 

I’m getting a value from textbox, Participant is the value from Textbox and im using Reactjs Class Component.
and have produced data like "attrs" : {"key":"value"} and here i want to assign it to Textbox value which is "Participant" : {"attrs" : {"key":"value"}} and store it inside config like

{

        "channel": "Domain",
        "config": {
            "countryCode": "91",
            "FieldOperationCompletedEvent": {
                "attrs": {
                    "ProductOrderId": "$.event.userTask"
                }
            }, 
            "Participant" : {
                 "attrs" : {
                      "key":"value"
                }
             }
      }
}

chrome.runtime.onMessage.addListener getting invoked on every tab open

I am building an extension in which content script is injected on context menu click. This functionality is working. Now the problem I am facing is that, whenever I open a new tab, the

chrome.runtime.onMessage.addListener

will get triggered without context menu click. How can I invoke the onMessage.addListener only on context menu click.

background.js



on_message = async(message, sender, sendResponse) => {
    console.log("bg.on_message");
    sendResponse("from bg");

    chrome.storage.local.get("list_url", function (data) {
        if (typeof data.list_url != "undefined") {
            urls = data.list_url
        }
    });
    chrome.storage.local.get("list_ip", function (data) {
        if (typeof data.list_ip != "undefined") {
            ips = data.list_ip
        }
    });
    chrome.storage.local.get("list_hash", function (data) {
        if (typeof data.list_hash != "undefined") {
            hashes = data.list_hash;
        }
    });

    if (hashes){
        hash_report = await createHashReport(hashes)
        hash_table = await createHashTable(hash_report)
        chrome.storage.local.set({
            "scanHash": true,
            "hash_table": hash_table
          }, () => {});
    }
    if (ips){
        ip_report = await createIpReport(ips)
        ip_table = await createIpTable(ip_report)
        chrome.storage.local.set({
            "scanIp": true,
            "ip_table": ip_table
          }, () => {});
    }
    if (urls){
        url_report = await createUrlReport(urls)
        url_table = await createUrlTable(url_report)
        chrome.storage.local.set({
            "scanUrl": true,
            "url_table": url_table
          }, () => {});
    }
    if ( hashes.length>0 || urls.length>0 || ips.length>0 ){
        chrome.windows.create({url: "output.html", type: "popup", height:1000, width:1000});
    }
}

chrome.runtime.onMessage.addListener(on_message);

genericOnClick = async () => {

    // Inject the payload.js script into the current tab after the backdround has loaded
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.scripting.executeScript({
            target: { tabId: tabs[0].id },
            files: ["payload.js"]
        },() => chrome.runtime.lastError);
    });
    
}

payload.js

function extract() {
    
    htmlInnerText = document.documentElement.innerText;
    url_exp = /[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}.[a-z]{2,4}b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?/gi;
    regex =  new RegExp(url_exp)
    list_url = htmlInnerText.match(url_exp)

    ip_exp = /bd{1,3}.d{1,3}.d{1,3}.d{1,3}b/;
    list_ip = htmlInnerText.match(ip_exp)

    hash_exp = /b[A-Fa-f0-9]{32}b|b[A-Fa-f0-9]{40}b|b[A-Fa-f0-9]{64}b/g
    list_hash = htmlInnerText.match(hash_exp)

    chrome.storage.local.set({ list_url: removeEmails(removeDuplicates(list_url)), list_ip: removeDuplicates(list_ip), list_hash: removeDuplicates(list_hash) });

}

chrome.runtime.sendMessage( extract())

Array push is not working when iterating through results in my API endpoint [duplicate]

So I have a problem with mongoose in my NextJS, the problem is that I’m trying to iterate a set of categories and the product of each results to add onto the variable products, but is not working, when I console log inside the loop, the products are printed but not added in the array, and this is so weird.

import { Product } from "../../models";
import { Response } from "../../utils";

export default async function ProductsFilters(req, res) {
  try {
    const { Cities, Categories, Sort } = req.body;

    let products = [];

    if (Cities.length > 0) {
      Cities.map(async (city) => {
        const results = await Product.find({ City: city });
        products.push(...results)
      });
    }

    if (Categories.length > 0) {
      Categories.map(async (category) => {
        const results = await Product.find({ Category: category });
        products.push(...results)
      });
    }

    if (products) Response(res, 200, true, "Të gjitha produktet u morën me sukses.", products);
    else Response(res, 404, false, "Asnjë produkt nuk u gjet në platformë.", null);
  } catch (error) {
    Response(res, 500, false, "Gabim i brendshëm i serverit gjatë gjetjes së produkteve.", null);
  }
}

react js useState update the quantity

I am new to react. I have got an issue updating a quantity.

const[persons,setPersons] = useState(personLists)

if you console.log(persons) it will give output as below. Now I want to
update qty for particular misc index of particular person index .
I have two persons in below array and each person have further two misc array


[
  {
    id: 1,
    name: "john",
    gender: "m",
    misc: [
      {
        id: 1,
        name: "xxx",
        qty: 1
      },
      {
        id: 2,
        name: "xxx1",
        qty: 1
      }
    ]
  },
  {
    id: 2,
    name: "mary",
    gender: "f",
    misc: [
      {
        id: 1,
        name: "aaa",
        qty: 1
      },
      {
        id: 2,
        name: "bbb",
        qty: 1
      }
    ]
  },
]

Now i want to update qty under misc array for that particular person.I have a function that takes the index of person array and index of misc array as below.

const updatePersonMiscQty = (personIndex, miscIndex) => {
  
 setPersons(persons =>

    persons.map((person,key) => {
    const found = person.misc.find(d => key === miscIndex);

    if (found) {
    found.qty += 1;
    }
    return person;
    })



}

let say my personIndex is 0 and miscIndex= is 1
so when usse click the button It should look into first person array, go to second index of misc and update qty.

I am looking for a solutions

Displaying values from a JavaScript dictionary in a HTML table

I am creating a webpage that uses a zip code to display map features from within that zip code. From the process of stripping the zip codes out of my map files I am several levels deep in if statements and functions. I need to get the final dictionary to display as one table on my HTML page. Right now because of the iteration it displays repeated values and completely fills up my page. How do I ensure the loop that is running is finished before looping through the final dictionary and writing it to the HTML page?

Here is my code, allFeaturesOne is a json dictionary object that is created before this set of loops it contains 150 fields. I’m also very much open to options that removes the nested functions I’ve created as I know its probably very ugly.

allFeaturesOne.forEach(searchFunction);
                  function searchFunction(value, index, array) {
                    var zipString = value.properties.ZIPCODE;
                    console.log (zipString)
                   var shortZip = zipString.slice(0, zipString.length-4);
                    console.log("slice String ", shortZip)
                    var strZip = ZipCode.toString();
                    if (shortZip == strZip) {
                      zipStore.push(value);
                      console.log("ZipStore is ", zipStore)
                     zipStore.forEach(showData);
                      function showData(value, index, array) {
                       let resultsArray = {"Name" : value.properties.BUSINESSNA,
                        "Address":value.properties.ADDRESS1, "City":value.properties.CITY
                        }
                        console.log('results array ', resultsArray)
                        for(let k in resultsArray) {
                          document.getElementById('target').innerHTML+="<tr><td>"+k+"</td><td>"+resultsArray[k]+"</td></tr>";
                        }
 <div class = 'layer-rows'>
                <div id = 'zipResults'>
                  <table id="target" border="1"></table>
                  
                </div>

How to implement websocket client in Electron (Next.js/React)?

I have a working websocket server. I use a websocket as client in web browser/react before, but I’m unable to use Websocket inside electron app since WebSocket depends on browser’s compatibility and for some reason, this feature is unavailable in Electron.

I use nextron (nextjs/react + electron) boilerplate.

import React from 'react';
import Head from 'next/head';
import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import { theme } from '../lib/theme';
import type { AppProps } from 'next/app';

export default function (props: AppProps) {
  const { Component, pageProps } = props;

  const ws = new WebSocket("ws://192.168.100.8:8081/")
  console.log("file: _app.tsx:11 ~ ws", ws)

  React.useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  return (
    <React.Fragment>
      <Head>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </React.Fragment>
  );
}

enter image description here