How does react work on a server in python?

I am beginning to learn react as a hobby, I am trying with a simple little project but I already have a difficulty that I do not find in other questions/answers:
I created the project via npx create-react-app my_app, in development via localhost:3000 the default page works, then I tried npm run build and the build folder was created

enter image description here

then I tried with my own test server in python pointing to the index.html page and I expected it to work the same, instead I have a page that doesn’t seem to take the css.
I noted that in the sources it looks for a couple of folders that are not included in the build folder:

enter image description here

I have no errors but I don’t understand why, do you have any idea why?
enter image description here

Sorry in advance for the triviality of the question but I’m new to front-end, I know a little html/js/ts/css but I’ve never used a framework and haven’t found much on the web, thank you very much!

Search in web, try to modify index.html in build folder

API call from extra-reducers fulfilled method

I have this a reducer slice like this-

const financialSlice = createSlice({
    name: 'financial',
    initialState,
    reducers: {

    extraReducers: (builder) => {
        //config
        builder.addCase(fetchFinancialConfig.pending, (state, action) => {
            state.data={};
            state.loading = true
        })
        builder.addCase(fetchFinancialConfig.fulfilled, (state, action) => {
            state.data={};
            let respConfig = action?.payload;
            state.config = respConfig;
            state.currentTag=respConfig.currentTag;
            state.currentPeriodType={value:respConfig.periodType};
            state.currentSheet=respConfig.currentSheet;

            let entityID = store.getState().currentTile.entityId;
            setPermissions(entityID, respConfig, state);
  
        });
        builder.addCase(fetchFinancialConfig.rejected, (state, action) => {
            state.data={};
            state.config = {}
        })
    }

Now I have a component which calls this createAsyncThunk method and sets the state.config as follows-

useEffect(() => {
    (async () => {
        try {
            dispatch(setMode(FINANCIALS));
            await FinancialsServices.getConfig();
        }
        catch (err) {
            console.log(err);
        }
    })()
}, []);

//useEffect responsible for fetching data as per grid mode
useEffect(() => {
    const getData = async (addParams) => {
        if ((financialState.config && Object.keys(financialState.config).length)) {
            await FinancialsServices.getData(getPayload(addParams));
        }
    }

   getData({})
}, [currentIndex, financialState.currentSheet.name,
    financialState.currentTag,
    financialState.currentPeriodType.value,
    financialState.currentCurrency, financialState.financialsGridMode])

this getData() and getConfig() functions are actually

static async getConfig() {
        try {
            const configResponse = await store.dispatch(fetchFinancialConfig());
            return configResponse.payload
        } catch (error) {
            console.log(error);
        }
    }

    static async getData(payload) { // makes a dispatch request to fetch data for perticular ratio
        try {
            const dataResponse: any = await store.dispatch(fetchFinancialData({ payload }));
            return dataResponse;
        } catch (error) {
            console.log(error);
        }
    }

Now in this fetchFinancialConfig.fulfilled
I want to make another API call thorugh setPermissions(entityID, respConfig, state); this function and change state variable state.permission=true or false

and I want this to execute before getdata useEffect and after fetching config through getConfig useEffect

How can I achieve it?
I tried calling this setPermission function in static async getConfig() { function, but it is being called after getData useEffect it does not wait for setPermission to finish executing

Is there any way to solve this problem?

***************************** UPDATE *****************************


I did something like-

builder.addCase(fetchFinancialConfig.fulfilled, (state, action) => {
            state.data={};
            let respConfig = action?.payload;
            state.config = respConfig;

            (async()=>{
                await setPermissions('123', respConfig, state)
            })();

and this seems to be working fine but now I want to access another slice to fetch entityId inside my slice.

Is there any way how we can do this?

I am encountering this error- when I tried store.getState()

You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.

querySelector return null even though DOM is loaded

This is my first time trying to make a Chrome extension. I want to track changes to an element on a page using MutationObserver, but I get null when trying to find the element I need. I checked for DOM loading – it didn’t help. Such an element definitely exists, I tried to run the code in the browser console – everything works.

I have this error

TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

manifest.json

{
  "manifest_version": 3,
  "name": "Helper",
  "version": "1.0",
  "action": {
    "default_popup": "helper.html",
    "default_icon": "helper_icon.png"
  },
  "content_scripts": [
    {
      "matches": [
        "*://*.site.ru/*"
      ],
      "js": [
        "./content.js"
      ],
      "run_at": "document_start",
      "all_frames": true
    }
  ],
  "web_accessible_resources": [{
    "resources": ["injected.js"],
    "matches": ["<all_urls>"]
  }]
}

content.js

console.log('content script start');

function run() {
    console.log('The DOM is loaded');
    let observer = new MutationObserver(mutationRecords => {
        console.log(mutationRecords);
    });
  
    observer.observe(document.querySelector('.items_9ujCP'), {
        childList: true, 
        subtree: true,
        characterDataOldValue: true
    });
    console.log(document.querySelector('.items_9ujCP')); // return null
}

document.addEventListener("DOMContentLoaded", run);

I’ve read similar questions, and it seems like everyone has a similar code working. I’d be glad if someone could help or explain what’s wrong.

Showing CSV Data in HTMl but not as a table

I am trying to show data from csv file into html using papa parse and js. I don’t want to show as a table, instead I want to show as a card using html and css styling but js can’t parse the csv. When I look at the console log, I don’t know why the results show html file when I clearly put the path as csv file.

My csv File:

image_path,name,description,price
/KMS/web-files/pop1.png,Product 1,This is the first product,10.99
/KMS/web-files/pop2.png,Product 2,This is the second product,12.49
/KMS/web-files/pop3.png,Product 3,This is the third product,8.99

My code:

    <div class="row sectionBlockLayout text-start" style="display: flex; flex-wrap: wrap; margin: 0px; min-height: auto; padding: 8px; align-items: center; width: 1166px; right: 0;">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>CSV Data Display</title>
      <style>
          .card {
              border: 1px solid #ccc;
              padding: 16px;
              margin: 8px;
              text-align: center;
          }
          .card img {
              max-width: 100px;
              height: auto;
          }
          .price {
              color: green;
              font-weight: bold;
          }
      </style>
  </head>
  <body>
  
  <div id="cards-container"></div>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
  <script>
  document.addEventListener("DOMContentLoaded", function() {
      fetch('./data.csv')
        .then(response => response.text())
        .then(data => {
          console.log('Raw CSV Data:', data);  // Log the raw CSV data to see if it was fetched correctly
          Papa.parse(data, {
            header: true,
            complete: function(results) {
              console.log('Parsed CSV Data:', results.data);  // Log the parsed data to see how it looks
              const container = document.getElementById('cards-container');
              results.data.forEach(row => {
                console.log('Row:', row);  // Log each row to see the structure
  
                const card = document.createElement('div');
                card.className = 'card';
                
                const img = document.createElement('img');
                img.src = row.image_path || 'default_image.jpg'; // Use a default image if image_path is missing
                img.onerror = () => img.src = 'default_image.jpg';  // Fallback in case of broken image link
                card.appendChild(img);
                
                const name = document.createElement('h3');
                name.textContent = row.name || 'No Name'; // Handle missing name
                card.appendChild(name);
                
                const description = document.createElement('p');
                description.textContent = row.description || 'No Description'; // Handle missing description
                card.appendChild(description);
                
                const price = document.createElement('p');
                price.className = 'price';
                price.textContent = `$${row.price || '0.00'}`; // Handle missing price
                card.appendChild(price);
                
                container.appendChild(card);
              });
            },
            error: function(error){
              console.error('Parsing error: ', error.message);
            }
          });
        })
          .catch(error => console.error('Error fetching CSV:', error));  // Log any errors that occur during the fetch
      });
  </script>
  
  </body>
  

</div>

This is my output

This is my output for now

Web worker inside react component causing race condition

I am trying to create a performant timer component in React.js (for learning purposes) and for that I am using web workers. The logic works as expected the first time when I click “Start” button but some weird race like condition starts appearing in countdown when I stop the counter and start again and then stop, only this time it won’t stop and timer speed accelerates!

Live code at: https://stackblitz.com/edit/timer-worker-wfs7e3

Trying to explain the process step by step:

Step Action Button State Timer State Note
1 Clicks “Start” Text updates to “Stop”. Color to “red” Active Timer starts as expected with speed as expected
2 Clicks “Stop” Text updates to “Start”. Color to “blue” Inactive Timer resets as expected
3 Clicks “Start” Text updates to “Stop”. Color to “red” Active Timer starts as expected with speed as expected
4 Clicks “Stop” Text updates to “Start”. Color to “blue” Active! Timer resets to 0 but doesn’t stop and starts running slightly faster
5 Clicks “Start” Text updates to “Stop”. Color to “red” Active! Timer resets to 0 but doesn’t stop and starts running even more faster

And so on. This keeps on happening until I refresh my page.
By the looks of it, seems that that there’s some race condition going on ( I maybe wrong) And I am unable to figure out the root cause. Is it bug or simply a failure at logical level?

// /src/workers/timer-worker.ts
const timerWorker = () => {
  let seconds = 0
  let timerId: number | null = null

  const INTERVAL = 100

  function dataFactory(time: number, status: "start" | "stop") {
    return { time, status }
  }

  self.onmessage = (event) => {
    if (event.data === "start") {
      seconds = 0
      timerId = setInterval(() => {
        seconds++
        self.postMessage(dataFactory(seconds, "start"))
      }, INTERVAL)
    }

    if (event.data === "stop") {
      seconds = 0
      self.postMessage(dataFactory(seconds, "stop"))
      clearInterval(timerId as number)
    }
  }
}

export default timerWorker
// /src/workers/web-worker.ts
export default class WebWorker {
    constructor(worker: any) {
        const code = worker.toString();
        const blob = new Blob(['('+code+')()']);
        return new Worker(URL.createObjectURL(blob));
    }
}

// src/components/Timer.tsx
import { FC, useEffect, useRef, useMemo, useState } from "react"
import { Timer as TimerStatus } from "../enums/timer"
import TimerWorker from "../worker/timer-worker"
import WebWorker from "../worker/web-worker"

export interface TimerProps {}

const Timer: FC<TimerProps> = () => {
  const [timerRunning, setTimerRunning] = useState(false)
  const [seconds, setSeconds] = useState(0)
  const workerRef = useRef<Worker | null>(null)

  const timer = useMemo(() => {
    const secs = seconds % 60
    const mins = Math.floor(seconds / 60) % 60
    const hrs = Math.floor(seconds / 3600) % 24
    const days = Math.floor(seconds / (3600 * 24))

    return `${days}d ${hrs}h ${mins}m ${secs}s`
  }, [seconds])

  const btnStyle = `btn ${timerRunning ? "btn-danger" : ""}`

  function initTimerWorker() {
    workerRef.current = new WebWorker(TimerWorker)
    workerRef.current.onmessage = (event) => {
      console.log(event.data)
      const { time, status } = event.data
      console.log(time, status)
      setSeconds(time)
    }

    // useEffect cleanup
    return () => workerRef.current?.terminate()
  }

  function clickHandler() {
    setTimerRunning((prev) => {
      const newState = !prev
      workerRef.current?.postMessage(
        newState ? TimerStatus.START : TimerStatus.STOP
      )
      return newState
    })
  }

  useEffect(initTimerWorker, [])

  return (
    <div
      id="Timer"
      className="place-self-center bg-white rounded-md p-4 w-80 text-center border border-solid border-slate-200"
    >
      <div className="text-3xl mb-2 font-bold">{timer}</div>
      <button className={btnStyle} onClick={clickHandler}>
        {timerRunning ? "Stop" : "Start"}
      </button>
    </div>
  )
}

export default Timer
// /src/enums/timer.ts

export enum Timer {
    START = "start",
    STOP = "stop"
}

Live code at: https://stackblitz.com/edit/timer-worker-wfs7e3

Very Strange Issue with GithHub Pages Failing to Load Local Audio Assets

I’m developing a webpage which is essentially a soundboard-site. I have a folder storing all of the audio files used by the page, which are being referenced by a json file with this type of pathing:

"threat_music/REGION/TH_REGION - SOUND.mp3"

Everything works totally fine locally on my computer when fetching the audio, but on the github page, while in a firefox browser, these two types of paths refuse to load their assets at all:

"threat_music/LF/TH_LF - SOUND.mp3"
"threat_music/HF/TH_HF - SOUND.mp3"

The paths used to fetch these audio files in the json file are correct and, like I said, are only causing issues when being hosted on the github page.

The error messages don’t help much since they’re all just “404” and “NS_BINDING_ABORTED”. I asked chatGPT for some solutions and tried them, which included checking file paths, encoding spaces, and cache issues, all to no avail. The audio files in the LF and HF folders never loaded, but audio files in other folders always did. I really have no idea what could be causing this to happen, and would love to just know the reason behind it.

Here’s the link to the page’s GitHub Repository and the page itself in case you want to take a closer look at what’s going on here.

Agenda (Node) defining a job with a variable name

I’m working on a rule engine in JavaScript that allows users to schedule when rules are checked. I’m using Agenda to the scheduling.

Ideally I want to define jobs with variable names so then whenever a rule is updated all I need is the id of the rule to see if an existing job for that rule already exsists. i.e. like “Execute Rule {id}”. But it seems like Agenda doesn’t recognize a matching job name unless it has the exact same name. How do I work around this ?

agenda.define('execute rule', async job => {
    console.log("running job");
    const { ruleMongObj } = job.attrs.data; // Accessing the job data attributes -- THIS IS THE FULL MONG OBJ
    const engine = new Engine();
    
    // Add the rule to the engine
    engine.addRule(rule.ruleMongObj);

    try {
        // Fetch facts for the user (subscriberId) from the backend
        const { subscriberId } = ruleMongObj;
        const factsResponse = await axios.get(`${backendBaseUrl}/fact/user/${subscriberId}/facts`);
        const facts = factsResponse.data;

        // Run the engine with the fetched facts
        const events = await engine.run(facts);

        if (events.length > 0) {
            events.forEach(event => {
                console.log(`Event triggered: ${event.type}`, event.params);
            });
        } else {
            console.log(`Rule ${rule._id} executed false`);
        }
    } catch (err) {
        console.error('Error running rule engine:', err);
    }
});

All I can think of right now is to create the job for the rule and then give the rule object in my backend a key to the job’s id so that every time that rule is updated we know if an existing job exists but I’d like a cleaner solution if possible.

As a note I am also not entirely sure if I can have the same job run on multiple time intervals? Any guidance on that would also help.

I tried simply passing in “execute rule {id}” which each new job but that doesn’t really work.

TypeScript Error: Implicitly has return type ‘any’ for Function with Recursive Call

So I have been trying to implement an Access and Refresh Token system for a while now.

I have had some success some failures. Some frustration. But overall I feel happy with my results.

I have come up with these API endpoints in my frontend to handle the refreshing (Which is not time-based but rather its supposed to be called on every action the user takes).

I have tried a similar approach in which I just do a react-query retry if the Access Token fails. I didn’t really feel like that was the best approach so I came up with this recursive call.

This is the endpoints that the react-query will call

export const checkAccessToken = async () => {
  const response = await fetch(`${API_BASE_URI}/api/auth/check-access-token`, {
    method: "POST",
    headers: {
      "Content-type": "application/json",
      Authorization: `Bearer ${localStorage.getItem("accessToken")}`,
    },
  });
  if (response.status === 401) {
    const result = await refreshAccessToken();
    if (!result) {
      throw new Error("Error while refreshing access token");
    }
    return checkAccessToken();
  }
  if (!response.ok) {
    throw new Error("Error while refreshing access Token");
  }
  const data = await response.json();
  return data;
};

And this is the function that gets called when the Access Token Fails

const refreshAccessToken = async () => {
  const response = await fetch(
    `${API_BASE_URI}/api/auth/refresh-access-token`,
    {
      method: "POST",
      credentials: "include",
    }
  );
  if (!response.ok) {
    return false;
  }
  const returnData = await response.json();
  localStorage.setItem("accessToken", returnData.accessToken);
  return true;
};

Which looks okay.. I guess I feel like its an improvement. But now the problem comes with typescript which gives me this error:

‘checkAccessToken’ implicitly has return type ‘any’ because it does
not have a return type annotation and is referenced directly or
indirectly in one of its return expressions.ts(7023)

I have never encountered this particular error So I am lost on how to fix it. I would really appreaciate if anyone can help me or guide me in how to fix this error.

These are the backend Endpoints in case they are necesary:

//Check the access token endpoints

export const checkAccessToken = (req: Request, res: Response) => {
  const authHeaders = req.headers.authorization;
  if (!authHeaders || !authHeaders.startsWith("Bearer ")) {
    return res
      .status(401)
      .json({ message: "Invalid or missing Authorization Header" });
  }
  const token = authHeaders.split(" ")[1]; //Crea un array y lo separa quedando de lugar 1 el token
  try {
    const decoded = jwt.verify(
      token,
      process.env.JWT_SECRET_KEY as string
    ) as AccessTokenType;
    if (!decoded) {
      return res.status(401).json({ message: "Unauthorized" });
    }
    return res.status(200).json({ message: "User Verified" });
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: "Internal Error 500" });
  }
};

// Refresh token Endpoints

export const refreshAccessToken = async (req: Request, res: Response) => {
      const token = req.cookies["refreshToken"];
      
      if (!token) {
        return res.status(401).json({ message: "Unauthorized" });
      }
    
      try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY as string) as RefreshTokenType;
    
        const cargoResult = await pool.query(
          "SELECT id_cargo FROM cargos_asignados WHERE id_empleado = $1 AND fecha_fin_asignacion IS NOT NULL",
          [decoded.id_empleado]
        );
    
        if (cargoResult.rows.length === 0) {
          return res.status(403).json({ message: "Forbidden: No active cargo found" });
        }
    
        const nameResult = await pool.query(
          "SELECT nombre FROM personas WHERE id_persona = $1",
          [decoded.id_empleado]
        );
    
        if (nameResult.rows.length === 0) {
          return res.status(404).json({ message: "Employee not found" });
        }
    
        const accessToken = jwt.sign(
          {
            id_empleado: decoded.id_empleado,
            cargo: cargoResult.rows[0].id_cargo,
            nombre: nameResult.rows[0].nombre,
          },
          process.env.JWT_SECRET_KEY as string,
          {
            expiresIn: "15m",
          }
        );
    
        res.status(200).json({ accessToken });
      } catch (error) {
        console.log(error);
        res.status(500).json({ message: "Internal Server Error 500" });
      }
    };

And also the types used for both the access and refresh token:

export type AccessTokenType = {
    id_empleado: string;
    cargo: number;
    nombre: string;
}

export type RefreshTokenType = {
    id_empleado: string;
}

Thats basically all my relevant endpoints. I am still learning about Auth so any feedback or input is really appreciated! Thank you for your time!

The data on my firebase dosen’t display on my website

Hi Im new to stackoverflow. Im creating a blogging website and the data(images, title, and date) on my firebase dosent display on my website.

let blogId = decodeURI(location.pathname.split("/").pop());

   // Define an async function to get the document
    async function getBlogData() {
       try {
           // Create a reference to the document
           const docRef = doc(db, "blogs", blogId);

           // Fetch the document data
           const docSnap = await getDoc(docRef);

           if (docSnap.exists()) {
            setupBlog(doc.data());
           } else {
               // Redirect to the homepage if the document doesn't exist
               location.replace("/");
           }
       } catch (error) {
           console.error("Error fetching document:", error);
       }
   }

   const setupBlog = (data) => {
    const banner = document.querySelector('.banner');
    const blogTitle = document.querySelector('.title');
    const titleTag = document.querySelector('.title');
    const publish = document.querySelector('.published');

    banner.style.backgroundImage = `url(${data.bannerImage})`;

    titleTag.innerHTML += blogTitle.innerHTML = data.title;
    publish.innerHTML += data.publishedAt;
   }

I tried to ask chatgpt but the code it gives dosen’t workyour text

Chrome Extension Microphone Access Issue

I’m developing a Chrome extension that adds a microphone button to Claude AI’s input field for voice input. However, I’m encountering issues with microphone access. The extension seems to default to using my iPhone as an input device instead of my computer’s microphone or connected AirPods Max. Obviously in any other audio requests it properly select the right source (Macbook microphone or Airpods)

Here’s my current manifest.json:

jsonCopy{
  "manifest_version": 3,
  "name": "Name",
  "version": "1.0",
  "description": "Adds a microphone button to Claude AI's input field",
  "permissions": ["activeTab", "storage", "audioCapture"],
  "host_permissions": [
    "https://claude.ai/*"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["https://claude.ai/*"],
      "js": ["content.js"]
    }
  ],
  "icons": {
    "48": "icon.png"
  },
  "web_accessible_resources": [
    {
      "resources": ["microphone-icon.svg", "config.js"],
      "matches": ["https://claude.ai/*"]
    }
  ]
}

Current Implementation

In my content.js, I’m using the following code to access the microphone:

javascriptCopyasync function startRecording() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
    // Rest of the recording logic
  } catch (error) {
    console.error('Error accessing the microphone:', error);
  }
}

The Problem
When I click the microphone button, the extension attempts to use my iPhone as the audio input device, ignoring both my MacBook’s built-in microphone and my connected AirPods Max. These devices work correctly in other applications.

  • Am I missing any crucial permissions or configurations in my manifest.json for proper microphone access?
  • How can I ensure my extension uses the correct audio input device (either computer microphone or connected headphones)?
  • Are there any best practices for handling audio device selection in Chrome extensions, especially when integrating with web applications like Claude AI?
  • Could there be any conflicts with Continuity Camera or other macOS features that might be causing this behavior?

Any insights, best practices, or potential solutions would be greatly appreciated. Thank you in advance for your help!

  • Verified Chrome’s microphone settings (chrome://settings/content/microphone)
  • Attempted to enumerate devices using navigator.mediaDevices.enumerateDevices()

In React Highchart, Lollipop chart is not rendering

I am using Highcharts v11.4.7 and while trying to render the Lollipop chart, it is throwing below error

Cannot read properties of undefined (reading 'prototype')

Below is the code I am using to import all the required libraries.

import Highcharts, { Options } from "highcharts";
import HighchartsReact from "highcharts-react-official";
import HighchartLollipop from "highcharts/modules/lollipop";
HighchartLollipop(Highcharts); // Bar chart loads fine if we comment this line

CodeSandbox can be referred to see the error.

I think it was working fine as such in previous versions of highcharts but cant seem to understand what I am doing wrong here..

Looking for an algorithm to split an image into the least possible amount of single-coloured rectangles

I am making a Javascript program which takes an image and returns it as a series of polygons for use somewhere else. I realised that it could be a lot more efficient if instead of every pixel being one polygon, the program could instead split the original image into rectangles which only contained pixels of one colour. I would like it to use the least possible amount of rectangles when doing this.

let red = "R = ["
      let green = "G = ["
      let blue = "B = ["
      let polygons = "["
      imagePreview.addEventListener('load', function (event) {
        red = "R = ["
        green = "G = ["
        blue = "B = ["
        polygons = "["
          const pixels = imgToPixels(this);
          for (let index = 0; index < pixels.data.length / 4; index++) {
            let pixelIdx = index * 4; // *4 because a pixel is 4 bytes
            let colour = 8//colour is what multiple each pixel should be rounded to.
            red += Math.round(pixels.data[pixelIdx]/colour)*colour + ","; 
            green += Math.round(pixels.data[pixelIdx + 1]/colour)*colour + ","; 
            blue += Math.round(pixels.data[pixelIdx + 2]/colour)*colour + ",";
            let x = index % imagePreview.naturalWidth;
            let y = (Math.floor(index / imagePreview.naturalWidth) * -1) + imagePreview.naturalHeight;
            polygons += "f(" + x + ","+ y +")" + ",";
          }
          red = red.substring(0, red.length - 1) + "]";
          green = green.substring(0, green.length - 1) + "]";
          blue = blue.substring(0, blue.length - 1) + "]";
          polygons = polygons.substring(0, polygons.length - 1) + "]";

Here’s the relevant part of the code. Rounding the RGB values is to decrease the amount of possible colours so that the next step is more effective at decreasing the polygon count. Problem is I don’t know how to do that next step. I’m just looking for the algorithm, you don’t need to implement it for me.

f(x,y) is a shorthand for polygon((x,y),(x+1,y),(x+1,y+1),(x,y+1)). It means that there is a square of size one(a pixel) at position (x,y). This would have to be changed after I implement this.

Why When debugging line by line vs. running all at once in Chrome JS, the output can differ, especially with objects?

when I try to console.log() the objects the output is different in console and when i debug line by line the console output is different.

var bikearray1 = [
  {
    manufacturer: 'bajaj',
    color: 'black',
    rpm: 1200,
    cc: 140,
  },
  {
    manufacturer: 'ktm',
    color: 'blackorange',
    rpm: 3000,
    cc: 240,
  },
  {
    manufacturer: 'hero-glamour',
    color: 'red',
    rpm: 500,
    cc: 100,
  }
];

var bikearray2 = bikearray1;

console.log(bikearray1);
console.log(bikearray2);

bikearray2[0].manufacturer = 'kawasaki';

console.log(bikearray1);
console.log(bikearray2);

I tried console logging but getting different outputs when debugging and when running whole code at a time
debugging line by line output

How do I avoid using setState inside of useEffect?

useEffect(() => {
    if (processed.length !== Object.keys(rules).length) {
      if (currRules.length) {
        const done = [],
          notDone = [];
        currRules.forEach((rule) => {
          const regex = new RegExp(rule);
          if (regex.test(password)) {
            if (rules[rule] === "The password digits should add upto 11") {
              console.log(rules[rule]);
              let chars = [...password],
                sum = 0;
              chars.forEach((char) => {
                console.log(Number(char));
                if (Number(char)) {
                  sum += Number(char);
                }
              });
              if (sum === 11) {
                done.push(rule);
              }
            } else {
              done.push(rule);
            }
          } else {
            notDone.push(rule);
          }
        });
        setProcessed([...processed, ...done]);
        setCurrRules([...notDone]);
      } else {
        for (const rule in rules) {
          if (!processed.includes(rule) && password) {
            setCurrRules([rule]);
            break;
          }
        }
      }
    }
    if (!password) {
      setCurrRules([...processed]);
      setProcessed([]);
    }
  }, [password, currRules]);

I have an input field which stores the password and I’m trying to match some password regex rules which I have stored in rules in the format {".{6,}": "The password should be minimum 6 characters", ...}. Rules are displayed below the password field in either green or red based on whether they are matched or not. I’m matching them one by one and storing them in processed as they get matched. currRules has the current rule that is being checked. Problem is I’m running into an infinite loop as I have to use setState to update the current and processed rules inside useEffect. How do I reconfigure my code to not run into this problem?