What could be causing the 404 Not Found error for PATCH and DELETE requests?

How can I ensure my mock server handles these methods correctly?

I’m building a React application that interacts with a mock API. I can successfully perform GET and POST operations, but I’m encountering issues with PATCH and DELETE requests, which return a 404 (Not Found) error. I’ve provided the relevant code below. Could anyone help identify what might be causing these errors?

here’s my code:

App.js:

`import Header from "./Header";
import Footer from "./Footer";
import ListItem from "./ListItem";
import "./index.css";
import { useState, useEffect } from "react";
import AddItem from "./AddItem";
import SearchItem from "./SearchItem";
import ApiRequest from "./ApiRequest";

function App() {
  const API_URL = "http://localhost:3500/items";
  const [items, setItems] = useState([]);
  const [newItem, setNewItem] = useState("");
  const [search, setSearch] = useState("");
  const [fetchError, setFetchError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchItems = async () => {
      try {
        const data = await ApiRequest(API_URL, { method: "GET" });
        setItems(data.items || []);
        setFetchError(null);
      } catch (error) {
        setFetchError(error.message);
      } finally {
        setIsLoading(false);
      }
    };

    setTimeout(fetchItems, 2000);
  }, []);

  const addItem = async (item) => {
    const id = items.length ? items[items.length - 1].id + 1 : 1;
    const addNewItem = { id, checked: false, item };
    const listItems = [...items, addNewItem];
    setItems(listItems);

    const postOptions = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(addNewItem),
    };

    try {
      await ApiRequest(API_URL, postOptions);
      setFetchError(null);
    } catch (error) {
      setFetchError(error.message);
    }
  };

  const handleCheck = async (id) => {
    const updatedItems = items.map((item) =>
      item.id === id ? { ...item, checked: !item.checked } : item
    );
    setItems(updatedItems);

    const updateOptions = {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ checked: updatedItems.find(item => item.id === id).checked }),
    };

    try {
      await ApiRequest(`${API_URL}/${id}`, updateOptions);
      setFetchError(null);
    } catch (error) {
      setFetchError(error.message);
    }
  };

  const handleDelete = async (id) => {
    const remainingItems = items.filter((item) => item.id !== id);
    setItems(remainingItems);

    const deleteOptions = {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
      },
    };

    try {
      await ApiRequest(`${API_URL}/${id}`, deleteOptions);
      setFetchError(null);
    } catch (error) {
      setFetchError(error.message);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!newItem) return;
    addItem(newItem);
    setNewItem("");
  };

  return (
    <div className="App">
      <Header name="To do List" />
      <AddItem
        newItem={newItem}
        setNewItem={setNewItem}
        handleSubmit={handleSubmit}
      />
      <SearchItem search={search} setSearch={setSearch} />

      <main>
        {isLoading && <p><b>Loading Items</b></p>}
        {fetchError && <p><b>{`Error: ${fetchError}`}</b></p>}
        {!isLoading && !fetchError && (
          <ListItem
            items={items.filter((item) =>
              item.item.toLowerCase().includes(search.toLowerCase())
            )}
            handleCheck={handleCheck}
            handleDelete={handleDelete}
          />
        )}
      </main>
      <Footer length={items.length} />
    </div>
  );
}`

export default App;

ApiRequest.js:

`const ApiRequest = async (url = "", optionsObj = {}) => {
  try {
    const response = await fetch(url, optionsObj);
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! Status: ${response.status}. Details: ${errorText}`);
    }
    return response.json(); // Return parsed JSON data
  } catch (error) {
    console.error('API request error:', error.message);
    throw error; // Rethrow the error for handling in calling function
  }
};
export default ApiRequest;`

Response:
Failed to load resource: the server responded with a status of 404 (Not Found)

Ag grid react selectcelleditor handleChange method

I want to know onChange method for ag-grid-react in selectCell editor.

I am editing the cells, when I select option from name dropdown its respective designation options should come.

But this is happening when I am existing edit mode and starting edit again.

I want to happen it live, when I select name , respective designation should come in dropdown of designation, without exiting edit mode.

Any other solutions are as well welcome.

{
field:"name",
headerName:"Name"
cellEditorSelector : (params:any)=>{
          return {
            component: "agSelectCellEditor" ,
            params:{values:nameArr},

          }
        },
field:"designation",
headerName:"Designation"
cellEditorSelector : (params:any)=>{
          return {
            component: "agSelectCellEditor" ,
            params:{values:designationArr},

          }
        }

}

Contenteditable: Some problems with creating and focusing span

I’ve been trying to solve this issue for a few days now but I don’t have any idea how I can fix it. I hope you can help me or give me some tips which lead me to the point to fix the issues.

I’m developing a feature in my app where it is possible to execute specific function on each sentence. Each sentence is assigned to a span element.

The browser’s default functionality destroys the entire functionality of the feature so I’m trying to add a custom functionality what happens if the user presses enter at the end of a sentence. My goal is to add a new line break with a new span each time when the cursor is at the end of the sentence and the user presses enter. The cursor should follow automatically the line breaks (go into the next row) and should focus the created span element that the input is assigned to the span.

I’ve tried to do it with the Selection-API and some things are working but not everything.

The things that aren’t working are:

  • move the cursor automatically into the next line
  • to focus the created span that the input is assigned to it and not inserted between the span elements (such as on the picture)

enter image description here

  • to add the line break and span at the end of a sentence outside the focused span (it doesn’t work, because I append the newly created spans as a child to the contentediable container.

In the contenteditable container should only be span elements on 1 layer without any deeper structure/layers.

How can I solve these isses?

This is my code:

public addOwnBehaviorToContentEditable(event: KeyboardEvent) {
    if (event.key !== 'Enter') return;

    event.preventDefault();

    let contenteditable = event.target as HTMLElement;
    let selection = this._document.getSelection();

    if (selection.rangeCount > 0) {
      let range = selection.getRangeAt(0);
      // Get the common ancestor container of the start and end nodes of the range
      let container = range.commonAncestorContainer;
      // Is the user in the last span element and at the end of the range (sentence) a new <br> and <span> element is created

      if (range.endOffset === container.textContent.length) {
        contenteditable.appendChild(this._document.createElement('br'));
        let span = this._document.createElement('span');
        span.textContent = '';

        this.assignPropertiesToSpan(span);
        contenteditable.appendChild(span);

        span.focus();

        let newRange = this._document.createRange();
        newRange.setStart(span, 0);
        

        selection.removeAllRanges();
        selection.addRange(newRange);
      } else {
        range.insertNode(document.createElement('br'));
      }
    }
  }

Why is req.body undefined in Multer’s diskStorage destination function?

I’m using Multer to handle file uploads in my Express.js application. I’m trying to access the req.body values in the destination function of Multer’s diskStorage option, but it’s returning undefined.how do i pass name from /registerartist to req.body of multer desination

Here’s my code:

import express from 'express';
import {json} from 'express';
import dotenv from 'dotenv';
import {mongoose} from 'mongoose'; 
import UserModel from './src/Models/usermodel.js';
import TrackModel from './src/Models/trackmodel.js';
import cors from 'cors';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import SingerSchema from './src/Models/singermodel.js';
import Artist from './src/Models/artistmodel.js';


dotenv.config();

const PORT = process.env.PORT;
const app = express();
app.use(json());
app.use(cors())
app.use(express.urlencoded({ extended: true }));



// Define __dirname for path resolution
const __dirname = dirname(fileURLToPath(import.meta.url));

// Multer Storage Configuration
const upload = multer({
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        const { name } = req.body; 
        const folderPath = `./uploads/artists/${name}`;
        console.log(folderPath)
        if (!fs.existsSync(folderPath)) {
          fs.mkdirSync(folderPath, { recursive: true });
        }
        cb(null, folderPath);
      },
      filename: (req, file, cb) => {
        cb(null, Date.now() + '-' + file.originalname);
      }
    })
  });
//connect to Database

mongoose.connect("mongodb://localhost:27017/Anitify")
.then(()=>{
    console.log("Connected to Mongodb")
})
.catch((err)=>{
    console.log("Error connecting to mongodb",err);
})




app.post('/registerartist', upload.single('image'),  (req, res) => {
    const { name, email, password, genre } = req.body;

  
    console.log("image is",req.file.image.originalname);
   
    console.log("bodyis",req.body.name);
  
   Artist.findOne({email:email})
   .then(result=>{
        if(!result){
            Artist.create(req.body);
        }else{
            console.log("already exists");
        }
   })
   .then(user=>res.json(user))
   .catch((err)=>{
        console.log(err);
        res.json(err)
   })
  });
  


issue in promise based taskRunner

I want to create a task runner which run based on limit for eg. limit=3 i.e. run 3 task at a time, but it is not executing after given limit; below is the main code ;

what could be the issue here?

class TaskRunner {
  #limit;
  #taskQueue = [];
  #taskCount = 0;

  constructor(limit) {
    this.#limit = limit;
  }

  run(fn, id) {
    this.#taskQueue.push({ task: fn, id: id });
     this.#taskCount++;
      while(this.#taskCount <= this.#limit && this.#taskQueue.length > 0) {
        const { task, id } = this.#taskQueue.shift();
        task(id).then((p)=>{
          console.log({p});
          this.#taskCount--;
        })
      }
    console.log(this.#taskCount);
  }
}

const taskRunner = new TaskRunner(3);

const task = (arg)=>{
  return new Promise((resolve)=>{
    setTimeout(()=>{
      console.log("Task Completed!", arg);
      resolve(true);
    }
    , 2000)
  }
  )
}
;

taskRunner.run(task, 'id-1');
taskRunner.run(task, 'id-2');
taskRunner.run(task, 'id-3');
taskRunner.run(task, 'id-4');
taskRunner.run(task, 'id-5');
taskRunner.run(task, 'id-6');
taskRunner.run(task, 'id-7');

or is there any better way to handle this?

How do i solve my crashing nextjs application?

i am currently facing a problem with my nextjs application.
As soon as I reload my page i get the following error message and my application crashes.
There are no problems on the first load. As soon as the error is there i have to restart my application.

Has anyone an idea what the reason could be?

Nextjs Error Message

Thank you!

I already tried reinstalling my node_modules but it didn’t solve the problem.

How to draw an arc on a Static Google Map in Javascript?

I wanted to draw an arc (refer the image below) on a static google map image.

Arc

I have created a web application that displays the Google Map. I have a search box and next button, the user can search whichever the place they want, zoom and set the required zoom to have a good picture of what they are looking. Upon clicking next button, I capture the map as a static image and display it inside a canvas. I have a button named arc which will draw the arc on top of the image inside the canvas.

But, my problem is I am not able to get the accurate distance. Say, the arc I am drawing is 20 meters from the center point (highlighted as red dot) to the end of the arc. When, I check with google map measure scale, I am getting a deflection of 5 to 8 meter, so mine is not accurate.

How do I get the accurate distance?

At the moment, I have used HTML2CANVAS to render a canvas, get the static image of the map and paste it inside the canvas. I have pretty much done with the logic for drawing the arc and I am focusing on making it accurate.

I am aware that map is now static image and I am drawing an arc on top of an image which is quite difficult in getting the accuracy, but is there any way I can pass the latitude and longitude and play with it?

Any idea and reference would be helpful, I can derive my logic from that.

Let me know if anyone needed the code, I am happy to post.

Thanks in Advance!

ApexChart timeline distributed legend

I have an ApexChart timeline, setted as distributed, but the legend doesn’t want to follow the distribution. How can I set the chart to show the legend for the bars?

chartOptions = {
            series: [{
                data: chartData
            }],
            title: {
                text: data.title,
                align: 'left'
            },
            chart: {
                type: 'rangeBar'
            },
            legend: {
                position: 'right',
                show: true,
                showForSingleSeries: true
            },
            plotOptions: {
                bar: {
                    distributed: true,
                    horizontal: true 
                }
            }
        };

bootstrap 5 collapse not working, button is not clickable

I try to create a collapse element according to the bootstrap document.

<!DOCTYPE html>
<html lang="fr" dir="ltr">

<head>
  <title>La Résidence Bloc H </title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta charset="UTF-8">
  <meta name="google-site-verification" content="xxx-YYY" />
  <meta name=“description“ content=“mmm.“>
  <link rel="stylesheet" href="css/style.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.css" integrity="sha512-UTNP5BXLIptsaj5WdKFrkFov94lDx+eBvbKyoe1YAfjeRPC+gT5kyZ10kOHCfNZqEui1sxmqvodNUx3KbuYI/A==" crossorigin="anonymous" referrerpolicy="no-referrer"
  />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css" integrity="sha512-sMXtMNL1zRzolHYKEujM2AqCLUR9F2C4/05cdbxjjLSRvMQIciEPCQZo++nk7go3BtSuK9kfa/s+a4f4i5pLkw==" crossorigin="anonymous"
    referrerpolicy="no-referrer" />
  <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

  <script>
    document.addEventListener("DOMContentLoaded", function() {
      fetch('header.html')
        .then(response => response.text())
        .then(data => {
          document.getElementById('header-tag').innerHTML = data;
        });
    });
    document.addEventListener("DOMContentLoaded", function() {
      fetch('footer.html')
        .then(response => response.text())
        .then(data => {
          document.getElementById('footer-tag').innerHTML = data;
        });
    });
  </script>
</head>

<body>

  <div id="header-tag"></div>
  <script>
    const hambuger = document.querySelector('.hambuger');
    const navMenu = document.querySelector('.nav-menu');

    hambuger.addEventListener("click", mobileMenu);

    function mobileMenu() {
      hambuger.classList.toggle("active");
      navMenu.classList.toggle("active");
    }

    const navLink = document.querySelectorAll('.nav-link');
    navLink.forEach((n) => n.addEventListener("click", closeMenu));

    function closeMenu() {
      hambuger.classList.remove("active");
      navMenu.classList.remove("active");
    }
  </script>
  <main>
    <section class="home" id="studio">
      <div class="box">
        <div class="text">
          <h4>50,000 CFA</h4>
          <h6>La chambre de luxe, chic et équipée, offre un mélange parfait de confort, élégance et technologie moderne. Dès l’entrée, un sentiment de sophistication et de détente se fait ressentir grâce à un décor harmonieux et soigné. Voici une description
            détaillée de cette chambre : </h6>

          <p>
            <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
                            Plus d'informations:
                        </button>
          </p>
          <div class="collapse" id="collapseExample">
            <div class="card card-body">
              <h5>Aménagement et Design</h5>
              ...
            </div>
          </div>
        </div>
      </div>
      <div class="image">
        <img src="image/g3.jpg">
      </div>
    </section>
  </main>
  
  <div id="footer-tag"></div>
</body>

</html>

The “Plus d’informations” is not clickable.

Javascript callback for when a child window is closed in Chrome

We’ve a simple popup window that opens to a shop.app checkout page, and we’re trying to hook into when a user has navigated away from there/closed the window, to then query the api and update information in their profile, if the checkout was successful.

I’ve tried a few methods, but a lot of this seems to be old, old javascript that doesn’t seem to work “right” any more? Most topics on this are 10+ years old on here.

    const events = [
        "afterprint",
        "beforeprint",
        "beforeunload",
        "gamepadconnected",
        "gamepaddisconnected",
        "hashchange",
        "languagechange",
        "message",
        "messageerror",
        "offline",
        "online",
        "pagehide",
        "pageshow",
        "popstate",
        "rejectionhandled",
        "storage",
        "unhandledrejection",
        "unload"
      ]

    let proxy = window.open(
      buyUrl,
      "child",
      "toolbar=no,location=no,directories=no,status=no,menubar=no,titlebar=no,fullscreen=no,scrollbars=1,resizable=no,width=430,height=220,left=500,top=100"
    )
    const listener = (title: string) => (event: unknown) => {
      console.log(title, event)
    }

    if (proxy) {
      events.forEach((eventType) => {
        proxy.addEventListener(eventType, listener(eventType))
      })
      proxy.onbeforeunload = listener("rawbeforeunload")
      proxy.onmessage = listener("rawmessage")
      proxy.onclose = listener("rawclosed")
    }

I got the list of events above from the keys of the WindowEventHandlersEventMap interface, just to see if I wasn’t hooking into the right one. Only 2 events are triggered, pagehide and unload, but both of those basically happen at the very same time, and only at the very start of the window’s lifecycle, when the page is rendered.

I’d mainly just like to know when that window is closed from a callback, but obviously none of the above is working right for what I want.

How to Update nzFooter of an ng-zorro-antd Modal After a Delay in Angular

Description:

I am working on an Angular project using ng-zorro-antd for modals. I need to dynamically update the footer of a modal after a certain delay (10 seconds). Initially, the modal should only have a “Cancel” button, and after 10 seconds, a “Regenerate OTP” button should be added to the footer.

Current Code:

Here’s the code I have so far:

import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';

export class SignupVerificationComponent {
  optModalRef!: NzModalRef;

  constructor(private modal: NzModalService) {}

  openOtpModal(id: number, isEmail: boolean): void {
    const modalTitle = isEmail ? 'Email OTP' : 'Phone Number OTP';
    this.optModalRef = this.modal.create({
      nzTitle: modalTitle,
      nzContent: OptComponent,
      nzFooter: [
        {
          label: 'Cancel',
          onClick: () => this.onCancelOtp(false, isEmail),
        }
      ],
      nzData: {
        isEmail: isEmail,
        userTempId: id,
        optModalRef: this.optModalRef,
      },
    });

    // Delay adding the "Regenerate OTP" button
    setTimeout(() => {
      if (this.optModalRef) {
        this.optModalRef.updateConfig({
          nzFooter: [
            {
              label: 'Cancel',
              onClick: () => this.onCancelOtp(false, isEmail),
            },
            {
              label: 'Regenerate OTP',
              onClick: () => this.generateOtp(isEmail),
            }
          ]
        });
      }
    }, 10000); // 10 seconds

    this.optModalRef.afterClose.subscribe((result) => {
      if (result) {
        if (isEmail) {
          this.isEmailVerified = true;
        } else {
          this.isPhoneNumberVerified = true;
        }
      }
    });
  }

  private generateOtp(isEmail: boolean): void {
    // Your OTP generation logic
  }

  private onCancelOtp(isRegenerate: boolean, isEmail: boolean): void {
    // Your cancel logic
  }
}

Problem:

The issue is that while the setTimeout function is executed after 10 seconds (as confirmed by the debugger), the modal’s footer does not get updated to include the “Regenerate OTP” button. The code hits the debugger statement inside setTimeout, but the footer remains unchanged.

What I’ve Tried:

  • Ensured that this.optModalRef is still valid and hasn’t been closed before calling updateConfig.
  • Logged the modal reference and confirmed it’s valid before attempting to update the footer.
  • Checked for any errors in the console but found none.

Desired Outcome:

After 10 seconds, the footer should be updated to include the “Regenerate OTP” button alongside the “Cancel” button without closing and reopening the modal.

Question:

How can I dynamically update the nzFooter of an ng-zorro-antd modal after a delay in Angular? Is there a better way to achieve this, or am I missing something in my current approach?

Show ‘Export’ button instead of icon in Fusion chart

I am using Fusion charts in my Laravel project. I have used exportenabled: 1 and the export icon is showing. I want to change that icon to text “Export”. I tried annotations but that doesn’t work.

const employeeSegmentationChartConfigs = {
  type: "pie3d",
  width: "1000",
  height: "450",
  dataFormat: "json",
  dataSource: {
    "chart": {
      "use3DLighting": "0",
      "showPercentValues": "1",
      "decimals": "1",
      "useDataPlotColorForLabels": "1",
      "theme": "fusion",
      "exportenabled": "1",
      "exportfilename": "employeeSegmentationExport",
      "paletteColors": "#7d7d7d,#C70814,#450E76,#9C28B1,#16938E, #C3C146,#532DDF, #7BC82D"
    },
    "data": employeeSegmentationData
  }
}

How to Automatically Separate Concatenated Email Addresses with Semicolons in an ASP.NET TextBox Using JavaScript?

`I am working on an ASP.NET Web Forms application where users need to enter multiple email addresses into a TextBox. Sometimes, users enter email addresses without any separators (e.g., binu.combinu.ae), and I need to automatically separate these with semicolons (;) when the input field loses focus.

I’ve implemented a basic solution using JavaScript to handle the blur event, but I’m facing issues when trying to intelligently split email addresses based on potential separators like “@” or “.”.

> > “`

`

Email Separator

function formatEmails() {
const emailInput = document.getElementById(‘<%= emailInput.ClientID %>’); // Replace with your input ID
let emailString = emailInput.value.trim();

const emailRegex = /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,})/g;

let result = ”;
let match;
let lastIndex = 0;your text

while ((match = emailRegex.exec(emailString)) !== null) {
Add the matched email to the result
result += match[0] + ‘;’;
lastIndex = emailRegex.lastIndex;

        }

Handle any remaining text that could be a partial email
if (lastIndex < emailString.length) {
result += emailString.substring(lastIndex).replace(/;/g, ”) + ‘;’;

        }

emailInput.value = result;

    }

document.addEventListener(‘DOMContentLoaded’, () => {
const emailInput = document.getElementById(‘<%= emailInput.ClientID %>’);
emailInput.addEventListener(‘blur’, formatEmails); (unfocus)

    });
</script>

`

`
““`

How can I improve my JavaScript function to reliably separate concatenated email addresses with semicolons in an ASP.NET Web Forms application? Are there any best practices or more robust regex patterns I should consider for this task?`

I am having trouble when Applying CSS to Dynamically Created Alerts and Prompts , Can any one there please guide me? [duplicate]

Problem:

I am trying to dynamically creat alerts and prompts using JavaScript functions, but struggling to apply CSS styles to these elements. The default browser styles are being applied, and I want to customize the appearance using CSS.

What I have tried:
here is the code I had used to try to apply css to dynamically created alert and prompt.

function showAlert(message) {
    alert(message);
    // Attempted to add styles directly
    document.getElementsByClassName('alert').style.color = 'red';
}

function showPrompt(question, defaultValue) {
    prompt(question, defaultValue);
    // Similarly tried to add styles
    document.getElementsByClassName('prompt').style.backgroundColor = 'lightblue';
}

However, these attempts have not successfully applied the desired CSS styles to the dynamically created alerts and prompts.

I am seeking guidance on the correct approach to apply CSS styles to these elements, and whether a different method of dynamic creation is needed to ensure styles are applied correctly.

useEffect and promise priority in inital and subsequent renders

I have below code and help me to find the output with accurate explanation.

'infiniteLoopProtection:false'
import * as React from "react";
import { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { screen, fireEvent } from "@testing-library/dom";

function App() {
  const [state, setState] = useState(0)
  console.log(1)
  
  const start = Date.now()
  while (Date.now() - start < 50) {
    window.timestamp = Date.now()
  }

  useEffect(() => {
    console.log(2)
  }, [state])

  Promise.resolve().then(() => console.log(3))

  setTimeout(() => console.log(4), 0)

  const onClick = () => {
    console.log(5)
    setState(num => num + 1)
    console.log(6)
  }
  return <div>
    <button onClick={onClick}>click me</button>
  </div>
}

const root = createRoot(document.getElementById('root'));
root.render(<App/>)

setTimeout(() => fireEvent.click(screen.getByText('click me')), 100)

Now I am confused how this can be.
Que: How promise and setTimeOut functions are executing before useEffect on initial render but after useEffect on subsequent render?

I tried running it on codeSandbox and got the below output

1
2
3
4
5
6
1
2
3
4

Even I executed the code in codeSandBox and got the same output. But https://bigfrontend.dev/react-quiz/useeffect-timing-iii is not accepting this answer. According to them correct answer should be

1
3
4
2
5
6
1
2
3
4