Chrome extension script opens a new tab, but runs the script in the original one

I’ve been fighting this for a couple of days now.
Basically I am on a website, and there is a text field in my extension which then opens a new tab and goes to the same website but with specific search terms. Then it needs to scrape that new tab, but instead it scrapes the original tab I was on. It correctly does the scrolling part of the script on the new tab, but the scraping itself is done on the original tab.

I have the following files:

background.js

content.js

manifest.json

popup.js

popup.html

I am not sure what exactly is the issue.
But here’s my background.js:

    //open a new browser window and navigate to the LinkedIn search URL
    chrome.action.onClicked.addListener((tab) => {
      // Open a new window
      chrome.windows.create(
        {
          url: "LINK",
          type: "popup",
          state: "maximized",
        },
        (newWindow) => {
          // Inject content script when the tab is fully loaded
          chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
            if (info.status === "complete" && newWindow.tabs[0].id === tabId) {
              chrome.scripting.executeScript({
                target: { tabId: newWindow.tabs[0].id },
                files: ["content.js"],
              });
              // Remove the listener after injecting the script
              chrome.tabs.onUpdated.removeListener(listener);
            }
          });
        }
      );
    });
    
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === "processPageData") {
        // Process the HTML content received from content script
        const pageHTML = request.pageHTML;
        // Send the page HTML to content script for processing
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          chrome.tabs.sendMessage(tabs[0].id, {
            action: "processPageData",
            pageHTML,
          });
        });
      }
    });

And this is my popup.js:

    document.addEventListener("DOMContentLoaded", function () {
      // Function to send LinkedIn search data to content.js
      document
        .getElementById("getDataButton")
        .addEventListener("click", function () {
          const searchKeywords = document.getElementById("searchField").value;
          const maxScrolls = document.getElementById("maxScrollField").value;
    
          if (!searchKeywords) {
            alert("Please enter search keywords.");
            return;
          }
    
          // Format the search keywords
          const formattedKeywords = searchKeywords.trim().replace(/s+/g, "%20");
          const searchUrl = `LINK`;
    
          // Send message to content.js in the currently active tab
          chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {
              action: "getLinkedInData",
              searchUrl: searchUrl,
              maxScrolls: parseInt(maxScrolls, 10) || 5, // Default to 5 if not a number
            });
          });
        });
    });

I suspect that the issue is here somewhere, but in case the content.js is needed as well it can be found here – https://pastebin.com/WzFx7GFq

Why is my fetch endpoint method seemingly not finishing? [duplicate]

So in my code, I have this function handling the clicking of a button. However, it seems like there is some problem holding up the fetch() function, since the “1” at the end never gets printed.

const handleSubmitCommentButton = async () => {
    console.log("0");
    await fetch("http://localhost:3001/postComment", {
        // const { author, comment, idOfParentPost, level } = req.body;
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body:
            JSON.stringify({
                author: "bob",
                comment: "commentToPost",
                idOfParentComment: "dunno",
                level: 0
            })
    });
    console.log("1)");
};

Here is the API endpoint associated with it. It seems to finish running, since in my code the “7” at the end is correctly printed to the console.

app.post("/postComment", async (req, res) => {
    const { author, comment, idOfParentPost, level } = req.body;

    const now = new Date();
    console.log("6");

    // Format the date to include only month, day, year, and time (hh:mm)
    const formattedDate = now.toLocaleString('en-US', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: true // or false for 24-hour format
    });


    const idOfParentComment = null;

    await db.collection("comments").insertOne({
        author, comment, idOfParentPost,
        level, idOfParentComment, createdAt: formattedDate
    });

    console.log("7");
    res.status(200).json({ success: true, message: 'Comment posted successfully' });
});

What could possibly be the issue?

I’ve tried to run print statements throughout my code to see what was happening. It seems like the fetch function finishes being called, but the code stops running after that and doesn’t print the “1” to the console like it should.

Scan white Barcodes with dark background

I’m currently working on a web project where I’m implementing a barcode scanner using HTML5, CSS, and JavaScript. The goal is to scan barcodes directly from the camera feed of a device and then perform specific actions based on the scanned barcode. The script is functioning well when scanning traditional black barcodes on a white background. However, I’ve encountered a significant issue when attempting to scan white barcodes on a black background.

Background and Context:

  • Project Setup: The project uses an HTML5 element to capture a live feed from the user’s camera. The video is displayed within a styled container on the webpage. I’m using the ZXing library to process the video feed and detect barcodes in real-time. The library decodes the barcode and maps it to a URL in a predefined database, which is then opened in the browser.

  • Problem Encountered: While the scanner works flawlessly with black barcodes (black lines on a white background), it struggles with white barcodes (white lines on a black background). Despite trying various approaches, the scanner consistently fails to detect white barcodes. This issue is perplexing since the detection logic should, theoretically, work with barcodes of any color, provided there’s sufficient contrast.

  • Attempts to Resolve: To solve this, I attempted to invert the colors of the video feed. I applied CSS filters to invert the colors, thinking that by treating white as black, the scanner might recognize the barcode. Unfortunately, this approach did not yield the desired results. The scanner still fails to detect the white barcodes, which makes me suspect that the issue might lie deeper in the way the barcode detection algorithm interprets the contrast or edges of the barcode lines.

Questions and areas where I need help:

  1. Understanding the Issue: What could be the reason that the barcode scanner fails to detect white barcodes on a black background? Is this a common limitation in barcode scanning technologies, or is there something specific to how the ZXing library processes video input that might cause this issue?
  2. Possible Solutions: Are there specific configurations or techniques within the ZXing library or in general barcode scanning practices that could help in improving the detection of white barcodes? Should I be looking into additional image processing techniques, such as contrast enhancement or edge detection, before passing the video feed to the barcode scanner?
  3. Library Suitability: Is ZXing the best choice for this task, or are there other libraries or tools that are more adept at handling different barcode color schemes? If so, what modifications or alternative libraries would you recommend?
  4. General Best Practices: For projects that need to support various barcode color schemes, what are some best practices or strategies to ensure reliable barcode detection across different colors and backgrounds?
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code-128 Barcode Scanner</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            overflow: auto;
        }
        #container {
            position: relative;
            width: 80vw;
            height: 40vw;
            max-width: 600px;
            max-height: 300px;
            background-color: black;
            border-radius: 10px;
            overflow: hidden;
            margin: 20px auto;
        }
        #preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <div id="container">
        <video id="preview"></video>
    </div>

    <!-- Erfolgs-Sound -->
    <audio id="successSound" src="https://www.orangefreesounds.com/wp-content/uploads/2018/11/Success-sound-effect.mp3" preload="auto"></audio>

    <script src="https://unpkg.com/@zxing/[email protected]"></script>
    <script>
        const codeReader = new ZXing.BrowserMultiFormatReader();
        let selectedDeviceId;

        const urlDatabase = {
            '5381674290': 'https://example.com/page2',
        };

        function handleResult(result) {
            const url = urlDatabase[result.text.trim()];
            console.log("Gelesener Code:", result.text);
            if (url) {
                console.log("URL gefunden, öffne:", url);
                document.getElementById('successSound').play();
                setTimeout(() => {
                    window.location.href = url;
                }, 5); 
            } else {
                console.log("Kein passendes URL gefunden.");
            }
        }

        function handleError(err) {
            console.error("Fehler beim Scannen des Barcodes:", err);
        }

        codeReader
            .listVideoInputDevices()
            .then((videoInputDevices) => {
                selectedDeviceId = videoInputDevices[0].deviceId;
                codeReader.decodeFromVideoDevice(selectedDeviceId, 'preview', (result, error) => {
                    if (result) {
                        handleResult(result);
                    } else if (error) {
                        handleError(error);
                    }
                });
            })
            .catch((err) => {
                console.error("Fehler beim Zugriff auf die Kamera:", err);
            });
    </script>

How to pass $DATE$ from HTML to JavaScript

I try to write a function that translates a date in English into long date in Polish.
The code looks as follows:

Html part:

<div class="blogitem">
   <$HEADING$ class="blogsubject">$SUBJECT$</$HEADING$>
   <p class="blogdate">
      <script type="text/javascript">document.write(date2polish($DATE$))</script>
   </p>
   <p class="blogthumb">$IMAGE$</p>
   $TEXT$
   <a class="blogbutton" href="$URL$" target="$TARGET$">$BUTTONTEXT$</a>
   <p><span class="blogcomments">$LABEL$ <a style="color: black;" href="mailto:$EMAIL$?subject=$SUBJECT$">$EMAIL$</a></span> </p>
</div>

and JS part:

DayT = new Array(7) 
DayT[0] = "niedziela" 
DayT[1] = "poniedziałek" 
DayT[2] = "wtorek" 
DayT[3] = "środa" 
DayT[4] = "czwartek" 
DayT[5] = "piątek" 
DayT[6] = "sobota"

MonthT = new Array(12) 
MonthT[0] = "stycznia" 
MonthT[1] = "lutego" 
MonthT[2] = "marca" 
MonthT[3] = "kwietnia" 
MonthT[4] = "maja" 
MonthT[5] = "czerwca" 
MonthT[6] = "lipca" 
MonthT[7] = "sierpnia" 
MonthT[8] = "września" 
MonthT[9] = "października" 
MonthT[10] = "listopada" 
MonthT[11] = "grudnia"

function date2polish(dateT){

    console.log("dateT = " , dateT);
    
    const tEMP = new Date(dateT);

    var Day = tEMP.getDate();
    var DayOW = tEMP.getDay();
    var Month = tEMP.getMonth(); 
    var Year = tEMP.getFullYear();
    
    return DayT[DayOW] + " , " + Day + " " + MonthT[Month] + " , " + Year;
}

I get the following result in console:

dateT =  0.0000823451910408432 
dateT =  0.00009881422924901186 
dateT =  0.0001646903820816864 
dateT =  0.0004940711462450593

As I understand 4 dates that are given like 01/01/2024, 01/03/2024, 01/05/2024 and 01/06/2024 are coded in some format that is not understood by js or am I wrong?

Could you please advise where I do the mistake?

I borrowed USDC which is my token1 But I’m receiving the loan in my WETH which is my token0, how do I solve this

I have done everything from beginning and it seems to work pretty well, untill I get to the part where I receive the loan.

I received the loan successfully but the problem is that I borrowed USDC which is my token1
But I’m receiving the loan in my WETH which is my token0

hich prints logs for debugging:

function uniswapV3FlashCallback(
uint256 fee0,
uint256 fee1,
bytes calldata data
) external {
require(msg.sender == address(pool), “not authorized”);

FlashCallbackData memory decoded = abi.decode(
    data,
    (FlashCallbackData)
);

console.log("Balance of token1 on contract(before paying off loan):"); 
console.log(token1.balanceOf(address(this)));
console.log("Balance of token1 on pool(before paying off loan):"); 
console.log(token1.balanceOf(address(pool)));

// Repay borrow
if (fee0 > 0) {
    token0.transferFrom(decoded.caller, address(this), fee0);
    token0.transfer(address(pool), decoded.amount0 + fee0);
}
if (fee1 > 0) {

    //Paying off the loan (back to the pool) with fee
    token1.transfer(address(pool), decoded.amount1 + fee1);
    console.log("Balance of token1 on contract (after paying off loan):"); 
    console.log(token1.balanceOf(address(this))); 
    console.log("Balance of token1 on pool (after paying off loan):"); 
    console.log(token1.balanceOf(address(pool))); 
}

// console.log("Fee0:");
// console.log(fee0);//0
console.log("Fee1:");
console.log(fee1);

}

why is my client sending a extra request to the server

io.on("connection", (socket)=>{
    console.log(socket.id)
    const cookiesHeader = socket.request.headers.cookie;

    if (cookiesHeader) {
        // Manually parse cookies
        const cookies = cookiesHeader.split(';').reduce((acc, cookie) => {
            const [key, value] = cookie.split('=');
            acc[key.trim()] = decodeURIComponent(value.trim());
            return acc;
        }, {});
        const token = cookies.Token
        console.log(token)
    }


   
})

Hello everyone,

I’m working on a project using Socket.IO, and I’m running into a couple of issues that I’m having trouble resolving. I would really appreciate any help or suggestions!

Multiple Requests:
My client seems to be sending two requests back-to-back to the server. I suspect this might be related to how the connection is being handled, but I’m not sure why this is happening. I would appreciate any insights or solutions for preventing this duplication of requests.

Slow Connection Establishment:
The connection between the client and server is taking a significant amount of time to establish. I’ve checked the network conditions and server performance, but the issue persists. Are there any common causes for slow connection times with Socket.IO or any recommended optimizations?

Axios Async/Await in Vue

Trying to use async/await on a get axios request. I am trying to save the response.data to transaction.value which is a Proxy object resulting in not able to use the ‘reduce’ function on it as it works on arrays. How can I save the response so its an array?

Below is my App.vue code:

<template>
    <PageHeader />
    <div class="container">
        <Balance :total="total" />
        <IncomeExpense :income="+income" :expense="+expense" />
        <TransactionList
            :transactions="transactions"
            @transactionDeleted="handleTransactionDeleted"
        />
        <AddTransaction @transactionSubmitted="handleTransactionSubmitted" />
    </div>
</template>

<script setup>
import PageHeader from './components/PageHeader.vue'
import Balance from './components/Balance.vue'
import IncomeExpense from './components/IncomeExpense.vue'
import TransactionList from './components/TransactionList.vue'
import AddTransaction from './components/AddTransaction.vue'

import { useToast } from 'vue-toastification'
import axios from 'axios'
import { ref, computed, onMounted } from 'vue'

const toast = useToast()

const transactions = ref([])

const fetchTransactions = async () => {
    try {
        const response = await axios.get('/data-api/rest/personaltransactions')
        transactions.value = response.data
        console.log(transactions.value)
    } catch (error) {
        console.log(error)
    }
}

onMounted(() => {
    fetchTransactions()
})

const total = computed(() => {
    return transactions.value.reduce((acc, transaction) => {  <---- 'reduce' error here
        return acc + transaction.transaction_amount
    }, 0)
})

</script>

Self-hosting a websocket in Python

I am trying to build a Jackbox-like game where a game is displayed on a screen (in Python), and the users connect to a website I host on GitHub pages where they can enter their answers.

I followed some tutorials to host a websocket server using Python or JavaScript via localhost; then, I followed another one that put the whole websocket/app on Heroku.

I would like to self-host the server while the game is on, via the websocket Python library. I know how to host a websocket on localhost; however, I am not sure if I can point to my IP and port directly from the GitHub page, or if I have to tunnel the activity on my port to another service…

Could you point me to the right direction?

Thanks 🙂

React Typeahead useState

Old coder/New to React,

I am attempting to use the typeahead to fill in address suggestions as the user starts to type in an address. I’ve set everything up as per the React Bootstrap Typeahead example page. Each time I attempt to autofill I can see the drop down appear with my results, but only for a second. The page refreshes (due to a data update which is expected React behavior). Unfortunately due to the refresh the drop down disappears. How is this not happening in the example?

Thank you in advance!

My Variables

const [addResult, setAddResult] = useState<Address[]>([]);   

The get Call

const getData = async (query: string) => {
     console.log('// onSearch/getData ');
     setIsLoading(true);

     try {
        
         const result = await getAddressSuggestion(query);
         console.log(result);
        

         console.log('// request made');
        
         if (result) {
           
            // console.log(result);
           
             //REFRESHES HERE AND DROP DOWN DISAPPEARS
             setAddResult(result.suggestions ? result.suggestions : []);
             console.log('// Set addResult');
               return;
         }
        
         setIsLoading(false);

     } catch (e) {
         console.log('Error: ' + e)
     }
 }
 const filterBy = () => true;

The Component
I added z-index because ideally I want it in a modal. The console lines are for understanding what is firing when.

<AsyncTypeahead className="select"
      z-index="1051"
      filterBy={filterBy}
      id={`address_${Date.now()}`}
      isLoading={isLoading}
      labelKey="zipcode"
      minLength={3}
      onSearch={getData}
      options={addResult}
      placeholder="Enter Address..."
      useCache={ false }
      onChange={(v) => {
          if (v.length)
              console.log('// onChange');
          else
              console.log('// onChange NO DATA');
      }}
      onInputChange={text => {
          console.log('// onInputChange')
      }}                  
      renderMenuItemChildren={(option: any, props) => (
          <PanelNoHeader>
              <span key={ option.zipcode}>{option.street_line} {option.secondary} {option.city} {option.state} {option.zipcode}</span>
          </PanelNoHeader>
      )}
  />

How to resolve the error of “Text strings must be rendered within a component” in React native?

I am building an app using React Native but I have an error saying “Text strings must be rendered within a component” error even though I don’t have any texts rendered outside the component.
This is the part the error occurs.


import React from "react";
import { SafeAreaView, StyleSheet, View } from "react-native";
import TopBar from "./Topbar";
import BottomNavBar from "./BottomNavbar";

const Layout = ({ children }) => {
  console.log("Children prop:", children);
  return (
    <SafeAreaView style={styles.container}>
      <TopBar />
      <View style={styles.contentContainer}>
        {children} {/* This is where the page-specific content will go */}
      </View>
      <BottomNavBar />
    </SafeAreaView>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#000000",
  },
  contentContainer: {
    flex: 1,
    marginBottom: 60, // Adjust to ensure content isn't hidden behind the navbar
  },
});

export default Layout;

import React from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ImageBackground,
  Image,
  Dimensions,
} from "react-native";
import Layout from "../layout/Layout"; // Import the Layout component

const { width, height } = Dimensions.get("window");

const Home = () => {
  return (
    <Layout>
      <ImageBackground
        source={require("../../../assets/home.jpg")}
        style={styles.backgroundImage}
      >
        <View style={styles.overlay} />

        <TouchableOpacity style={styles.button}>
          <Text style={styles.buttonText}>Enjoy The Game</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button}>
          <Text style={styles.buttonText}>Find Your Match</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button}>
          <Text style={styles.buttonText}>Plan Your Date</Text>
        </TouchableOpacity>
      </ImageBackground>
    </Layout>
  );
};

const styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    width: width,
    height: height,
  },
  overlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0, 0, 0, 0.4)",
  },
  button: {
    width: width * 0.8,
    padding: 15,
    borderRadius: 50,
    borderWidth: 2,
    borderColor: "#ffffff",
    justifyContent: "center",
    alignItems: "center",
    marginVertical: 10,
    backgroundColor: "rgba(255, 255, 255, 0.1)",
  },
  buttonText: {
    fontSize: 20,
    color: "#ffffff",
    fontFamily: "Playfair",
  },
  cursorIcon: {
    position: "absolute",
    width: 30,
    height: 30,
    right: -35,
    top: -10,
  },
});

export default Home;

I tried to find out the source of error by commenting out each component in pages.
The error seems to be in the childrens prop in the Navbar component.
I don’t have any texts rendered outside the component here.
Could somebody help with this?

Asynchronous functions and useEffect re-rendering issue

I am build a page in React application where I am using useEffect to call an API,

const customer_ids = useSelector((state) => state.test.customersOptions);
const office_ids = useSelector((state) => state.test.officesOptions);
const debounceTimeout = useRef(null);
const DEBOUNCE_DELAY = 1000;

const selectedCustomerArray = useSelector(
  (state) => state.test.selectedCustomers
);
const selectedOfficeArray = useSelector(
  (state) => state.test.selectedOffices
);

useEffect(() => {
  if (!customer_ids.length) {
    return;
  }
  dispatch(setSelectedCustomers(customer_ids.map((customer) => customer.id)));
}, [customer_ids]);

const filteredOffices = useMemo(() => {
  return office_ids.filter((office) =>
    selectedCustomerArray.includes(office.org_id)
  );
}, [selectedCustomerArray]);

useEffect(() => {
  dispatch(setSelectedOffices(filteredOffices.map((office) => office.id)));
}, [filteredOffices]);

useEffect(() => {
  if (debounceTimeout.current) {
    clearTimeout(debounceTimeout.current);
  }

  debounceTimeout.current = setTimeout(() => {
    fetchData();
  }, DEBOUNCE_DELAY);

  // Cleanup function
  return () => {
    clearTimeout(debounceTimeout.current);
  };
}, [selectedCustomerArray, selectedOfficeArray]);

The problem is when I do all this it triggers a useEffect re-render of death and it calls all the APIs 3 times. I have tried my best to solve this issue but I am unable to do so.

What I truly want is when customerIds and officeIds are fetched from the server on page load, auto select all the customers and offices in selectedCustomers and selectedOffices respectively.

Then when there is change in those two state values, I call the API.

I have tried useMemo(), useCallBack(), nothing has worked. I also tried using useRef and compare the previous value and the new value and it still doesn’t work.

Legacy AngularJS App: Strange undefined properties error after changing from .js to .ts file

I am working on a legacy AngularJS app which will need to switch to using typescript. I installed typescript via NPM, and converted a component from .js to .ts file. However, the component page now shows this weird error:

angular.min.js:118 TypeError: Cannot read properties of undefined (reading '$routerOnActivate')
    at Object.link (https://localhost:44347/app/assets/js/vendor/angular_1_router.js:190:34)
    at https://localhost:44347/app/assets/js/vendor/angular.min.js:16:71
    at la (https://localhost:44347/app/assets/js/vendor/angular.min.js:81:90)
    at p (https://localhost:44347/app/assets/js/vendor/angular.min.js:66:341)
    at g (https://localhost:44347/app/assets/js/vendor/angular.min.js:58:481)
    at https://localhost:44347/app/assets/js/vendor/angular.min.js:58:119
    at Object.link (https://localhost:44347/app/assets/js/vendor/angular_1_router.js:177:41)
    at https://localhost:44347/app/assets/js/vendor/angular.min.js:16:71
    at la (https://localhost:44347/app/assets/js/vendor/angular.min.js:81:90)
    at p (https://localhost:44347/app/assets/js/vendor/angular.min.js:66:341) <not-found $router="::$$router" class="ng-scope">

The page works fine when using .js extension, what might be the cause of this issue?

Greasemonkey script to automatically add bcc on outlook web interface

auto bcc

I wish to automatically add bcc address while composing email on Outlook web interface.
While there are such outbound rules on Outlook Desktop, Outlook web interface only supports incoming rules. So it seems that there is no way to set up auto bcc on the outlook web interface.

Here are the most recent post 1 and 2 on Microsoft forums, which specifically says that Outlook web interface does not support this feature, and it looks like the new version Outlook Desktop also removes the feature.

So I’m thinking to write a greasymoney script that can automatically fill in the bcc field every time when I compose/reply to an email. The flow should be to monitor any event of composing, replying, replying all and forwarding event; once the new message window pops out, the program automatically fills in the desired address.

But I don’t know too much about javascript, and would like to get some help here setting up the code.

Other viable suggestions without using greasemoney is also welcome (But I probably won’t be able to write a Firefox plugin for that matter.) And I wish to stick to the web interface.

Thanks in advance!

Mutating an ES6 Map while iterating with forEach

In my ES6 <String,Boolean> Map, I need to change all keys that end with :1 to false in a button-click function.

I’m using the forEach(v,k) Map method. For some reason it includes the Value as the 1st param and the Key as the 2nd param (I would have thought it would be the opposite), and also I only need to scan the keys, not the values.

My concern is, is it safe to mutate the map while iterating this way? In this case I’m not adding new keys, I’m just mutating the value. If I did add new entries, would the forEach pick it up or still iterate the old entries?

 const handleBackButton = () => {
    errorMap.forEach((value:boolean, key:string) => {
        if (key.endsWith(":1")) {
            errorMap.set(key, false);
        }
    });

React state showing weird behavior

I am new to react and making a simple shopping cart for a coffee shop. whenever i add a item to cart if the item is not already in cart then i basically add it in with the rest of the items and set quantity property to 1 and whenever i add the same item again i just take the whole items and update the corresponding items quantity by doing quantity++. But i don’t know why the quantity gets updated by two on its own. i have tried debugging it but i cant get it that why is this happening that why isn’t it updating by 1 and instead getting updated by 2.

Here is my app component -:

import CoffeeShop from "./CoffeeShop"

function App() {

  return (
    <>
      <h1 style={{ textAlign: "center" }}>Coffee Shop</h1>
      <CoffeeShop />
    </>
  )
}

export default App

This is my CoffeeShop component -:

In this component i am handling the add to cart behavior

import "./CoffeeShop.css";
import CoffeeItems from "./CoffeeItems";
import ShoppingCart from "./ShoppingCart";
import { useState } from "react";

export default function CoffeeShop() {

    const [cartItems, setCartItems] = useState([]);
    const [totalPrice, setTotalPrice] = useState(0);

    const addToCart = (id, item) => {
        console.log(cartItems);
        setCartItems(currItems => {
            const idx = currItems.findIndex(cartItem => cartItem.id === id);
            if (idx !== -1) {
                const newItems = [...currItems];
                newItems[idx].quantity++;
                return newItems;
            }
            return [...currItems, { ...item, quantity: 1 }];
        });
        setTotalPrice(currTotalPrice => currTotalPrice + item.price);
    };



    return (
        <div className="CoffeeShop">
            <CoffeeItems addToCart={addToCart} />
            <ShoppingCart cartItems={cartItems} totalPrice={totalPrice} />
        </div>
    );
}

This is my CoffeeItems component -:

import { useEffect } from "react";
import { useState } from "react";
import fetchProducts from "./productsApi";
import CoffeeItem from "./CoffeeItem";
import "./CoffeeItems.css";
import { v4 as uid } from "uuid";

export default function CoffeeItems({ addToCart }) {

    const [products, setProducts] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            const data = await fetchProducts();
            setIsLoading(false);
            for (let product of data) {
                product.id = uid();
            }
            setProducts(data);
        }
        fetchData();

    }, []);


    return (
        <div className="CoffeeItems">

            {isLoading && <h1>Loading...</h1>}
            {products.map(product => <CoffeeItem product={product} addToCart={addToCart} key={product.id} />)}

        </div>
    );
}

**The CoffeeItems component basically fetches mock data where each product like : **

{
        "id": 3,
        "name": "Tea set",
        "price": 39.99,
        "description": "This tea set is a complete tea-making solution for tea enthusiasts. It consists of a beautiful and functional kettle for boiling water and a set of delicate tea cups designed for serving tea. The kettle is made of ceramic and comes with a handle and spout for easy pouring. The tea cups are small and dainty with a simple yet elegant design. Whether for a quiet afternoon tea with a friend, a family gathering, or a special event, this tea set offers a classic and sophisticated way to enjoy a relaxing cup of tea.",
        "image": "alisher-sharip-mumpl9-D7Uc-unsplash.jpg"
    }

This is my CoffeeItem component -:

import "./CoffeeItem.css";

export default function CoffeeItem({ product, addToCart }) {

    const handleAddToCart = (e) => {
        e.preventDefault();
        addToCart(product.id, product);
    }

    return (
        <div className="CoffeeItem">
            <h2>{product.name}- ${product.price}</h2>
            <img src={product.image} alt="product image" />
            <div>
                <button onClick={handleAddToCart}>Add to cart</button>
            </div>
        </div>
    );
}

This is my ShoppingCart component -:

import "./ShoppingCart.css";
import CartItem from "./CartItem";

export default function ShoppingCart({ cartItems, totalPrice }) {

    return (
        <div className="ShoppingCart">
            <h1>Shopping Cart</h1>
            {cartItems.length === 0 && <h2>Your cart is empty</h2>}
            {cartItems.length > 0 && <h2>total: ${totalPrice}</h2>}
            {cartItems.map(cartItem => <CartItem cartItem={cartItem} key={cartItem.id} />)}
        </div>
    );
}

**This is my CartItem component -: **

import "./CartItem.css";

export default function CartItem({ cartItem }) {
    return (
        <div className="CartItem">
            <h2>Name: {cartItem.name}</h2>
            <h3>Price: ${cartItem.price}</h3>
            <h3>Quantity: {cartItem.quantity}</h3>
        </div>
    );
}

In the CoffeeShop component when addCart handler is executed for a some item which is already in the cart it in the code it adds +1 right. but it actually adds +2 to the quantity property of the respective product. I don’t know why is this happening. Please help.

EDIT

I just removed from the main.jsx file and everything is working fine now. but why ?

This is the main.jsx file

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import './index.css'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

**When i remove everything works fine. but why ? **