How to change the style of a specific list item on click in React.js?

I am a beginner when it comes to coding with React or JS.

I was trying to create a To-Do list wherein I can add or delete tasks (which I have already accomplished). However, I wanted to add another functionality of a ‘Done’ button which will strike through the specific task item on click.

My react code areas of interest look like this:

function Todo(){

    const [tasks, settask] = useState([]);
    const [newtask, setnewtask] = useState("");

    function handle_change(event){
        setnewtask(event.target.value);
    }

    function update_todo(){

        if(newtask!=""){        
            settask(t => [...t, newtask]);
            setnewtask("");}
    }

    function delete_task(index){
        const a = tasks.filter((_, i) => i!=index);
        settask(a);
    }

    function strike(index){
        // const striked = {textDecoration: "line-through"};
        tasks[index].style.textDecoration = "line-through";  
    }


    return(
        <div id="main">
            <h1>To-Do List</h1>
            <div id="add">
                <input type="text" id="add_item" placeholder='Enter your task' value={newtask} onChange={handle_change}></input>
                <input type="button" id="add_button" onClick={update_todo} value="Submit"></input>
            </div>
            <div id="list">
                <ol>{tasks.map((element,index) => <li key={index}>
                    <div className="list_item">{element}</div>
                    <div className="button_container">
                        <button className="delete" onClick={() => delete_task(index)}>Delete</button>
                        <button className="done" onClick={() => {strike(index)}}>Done</button>
                        </div>
                    </li>)}
                </ol>
            </div>
        </div>
    )
}

I have implemented the above code, but the done button functionality is doing nothing, I tried multiple ways but none of them is working.

enter image description here

React OnClick event not passing parameter, rather passing SyntheticBaseEvent

I am creating a modal. This modal will be opened when any of 6 div elements are clicked. Each of the components are created using the .map() function to an array. The popup parameter is supposed to be the function that runs when clicked:

items.map(item => (
  <StoreItem popup={() => popup} item={item} />
))         

For each item from items, there is a StoreItem created. Here is the code for the StoreItem component:

const StoreItem = ({popup, item}) => {
  return (
    <div onClick={popup(item)} className="...">
    ...
    </div>
  );
};

As seen above, each StoreItem is a div with an onClick property that runs the popup() function. Here’s the popup() function:

function popup(item) {
    console.log(item);
}

For some reason, when I console.log(item), the item that is supposed to be passed in from the onClick is not being logged. Rather, I’m getting a SyntheticBaseEvent with random stuff that I don’t want.

How is this fixed so that the contents of item are properly displayed, not some SyntheticBaseEvent?

Thanks, any help is appreciated.

Its possible to use q-timeline-entry inside q-intersection component?

I am trying to show a timeline using the timeline component, since the timeline is goint to be pretty big, I tried to use the intersection component so each timeline entry will only be in the DOM when “seen”, so I have something like this:

<div class="q-px-lg q-py-md">
  <q-timeline color="secondary">
    <!-- START: list -->
    <q-intersection
      v-for="item in allItems"
      :key="`item-${item.id}`"
      class="example-item"
    >
      <q-timeline-entry
        :title="item.product?.name"
        :subtitle="item.legend"
      >
        <div>
          {{ item.desc }}
        </div>
      </q-timeline-entry>
    </q-intersection>
    <!-- END: list -->
  </q-timeline>
</div>

I see the intersection component working, but the timeline doesnt have the connecting lines, its missing the q-timeline__dot::after CSS,
Am I missing something? should I use the directive instead and do the DOM add/remove with it?

Back Arrow In Edge – Value In JS Doesn’t Match Dropdown Selection

I’m having an issue when clicking the back arrow in Microsoft Edge, for a shopping cart that sends various select options to different PHP files via Ajax. I’ve never had back arrow working correctly in Edge or Chrome, but I’ve now decided I’d like to try and fix it.

Therefore, I’ve created a small test program that demonstrates the problem perfectly. You’ll notice that I’ve included the code (two HTML files), and a 33 second video which shows the test program running, with Edge on the left and Firefox on the right.

As shown in the video, the steps to reproduce the issue are as follows…

  1. Select option 2
  2. Navigate to page 2 by clicking the link
  3. Click the back arrow

Here’s the video: https://youtu.be/J3tLFXjPDdA

When the page loads after clicking the back arrow, the JS runs again, i.e. by default in Edge for this example bfcache is disabled, but for Firefox I’ve disabled bfcache with window.onunload

Here’s the problem… within window.onload, getElementById(“options”).value returns “option-1” after clicking back arrow, which does not match the selected option “Option 2” that is visible.

Bizarrely, I then discovered that just by delaying the call to getElementById(“options”).value by setting setTimeout(), the value returned then becomes “option-2” which is correct. Keep in mind that this code is inside window.onload.

I don’t want to simply reload the page on back arrow as a fix. I’d much rather learn why this mismatch of visible selection vs returned value is happening… and it is only in Edge and Chrome.

To run the test program, for each of the two pages simply copy the code into a text file and change the extension to .htm, and then right click on …page-1.htm and select open with Edge.

<!DOCTYPE html>

<label for="options">Select Option</label>
<select id="options">
  <option value="option-1">Option 1</option>
  <option value="option-2">Option 2</option>
</select>

<a href="back-arrow-issue-page-2.htm">Page 2</a>

<script>
  window.onpageshow = function(event) // testing for bfcache
  {
    if (event.persisted)
      alert("From bfcache");
  };

  window.onunload = function(){}; // disables bfcache in Firefox when running an htm file from a local drive, so that the script will run for a second time, i.e. after clicking back arrow. Note: this doesn't disable bfcache when running a local htm file in Safari

  window.onload = function()
  {
    console.log("in: window.onload");
    let performance_entries = performance.getEntriesByType("navigation");

    for (var i = 0; i < performance_entries.length; ++i)
    {
      console.log(performance_entries[i].type);

      if (performance_entries[i].type == "back_forward")
      {
        console.log(document.getElementById("options").value);
        setTimeout(delay_test, 0); // 1 worked, and so I then tried 0 which also works
      }
    }
    function delay_test()
    {
      console.log(document.getElementById("options").value);
    }
  }
</script>
<!DOCTYPE html>

<a href="back-arrow-issue-page-1.htm">Page 1</a>

Cheers, Gary.

Why doesn’t it work with the Shadcn library?

I’m having trouble submitting a form while using the “shadcn” library, it just doesn’t respond at all. When I’m testing without a library, the form is nicely sent and submitted. Is there anyone who can help me? I use Vite to develop an app via React.
////////////////////////////

Register Component:

import React from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import {
  Form
} from "@/components/ui/form";
import LinkButton from "@/components/Button";
import Navbar from "@/components/Navbar";
import RegisterForm from "@/components/RegisterForm";


const schema = z
  .object({
    username: z.string().min(2),
    password: z.string().min(8),
    confirmPassword: z.string().min(8),
    email: z.string().email(),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ["confirmPassword"],
  });

export const Register = () => {
  const navigate = useNavigate();
  const methods = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      email: "",
      username: "",
      password: "",
      confirmPassword: "",
    }
  })

  const { handleSubmit, control, formState: { isSubmitting } } = methods;

  const onSubmit = async (values) => {
    console.log("Form values:", values);
    const { username, password, email } = values;
    try {
      console.log("Attempting to register user...");
      const response = await axios.post("/api/auth/register", {
        username,
        email,
        password,
      });
      console.log(response.data);
      navigate("/login");
    } catch (error) {
      console.error("Error during registration:", error);
    }
  };
  console.log("Render Register component");
  return (
    <div>
      <Navbar />
      <div className="flex justify-center items-center h-screen">
        <Form {...methods}>
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="space-y-6 p-4 xl:w-1/2 md:w-1/2 sm:w-1/2 xs:w-full xs:p-5 shadow-md"
          >
            <RegisterForm name="username" label="Username" placeholder="Username" inputType="username" formControl={control}/>
            <RegisterForm name="email" label="Email" placeholder="Email" inputType="email" formControl={control}/>
            <RegisterForm name="password" label="Password" placeholder="Password" inputType="password" formControl={control}/>
            <RegisterForm name="confirmPassword" label="Confirm Password" placeholder="Confirm Password" inputType="password" formControl={control}/>
            <LinkButton
              type="submit"
              className="w-full bg-bg-btn-prm"
              disabled={isSubmitting}
            >
             {isSubmitting ? "Loading..." : "Register"}
            </LinkButton>
          </form>
        </Form>
      </div>
    </div>
  );
};

RegisterForm component:

import React from 'react';
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from './ui/form';
import { Input } from './ui/input';

const RegisterForm = React.memo(({ name, label, placeholder, inputType = 'text', formControl }) => {
  console.log(`Rendering field: ${name}`);

  return (
    <FormField control={formControl} name={name} render={({ field }) => (
      <FormItem>
        <FormLabel>{label}</FormLabel>
        <FormControl>
          <Input placeholder={placeholder} type={inputType} {...field} />
        </FormControl>
        <FormMessage />
      </FormItem>
    )} />
  );
});

export default RegisterForm;

data not getting updated in template ref modal after opening in angular

I have a login screen where my component has 2 template refs as a modal. One for loading bar and another is for any kind of error

I’m able to send Logging in.. text in loading bar. But while trying to login if there’s any error, the second template ref is supposed to show error. The error text is logging in console log before opening the template but not getting displayed on modal. Modal is opening but it is showing blank screen. Here is the html code

<ng-template #loadingTemplate let-data>
    <div class="loadingBar" >
        <p class="loading-note" >{{data.message}}</p>
        <mat-spinner></mat-spinner>
    </div>
</ng-template>
<ng-template #modalRoleSelect let-data>
    <div class="loadingBar" >
        <p class="loading-note2">{{data.loginText}}</p>
    </div>
    <div style="display: flex;justify-content: flex-start;" >
        <button style="margin: 10px 20px;font-weight: bold;letter-spacing: 0.5px;" mat-raised-button (click)="closeDialog()" >Close</button>
    </div>
</ng-template>

Here is the typescript code

openTemplate(error:string) {
      console.log(error)
      const dialogRef1 = this.dialog.open(this.customTemplate, {
          data: {loginText:error},
         width: '470px'
      });
      dialogRef1.afterClosed().subscribe(() => {
        console.log('The dialog was closed');
      });
  }

While the modal is in opened state, if i try to click any radio buttons the error is showing.
I’m guessing something wrong with change detection

Can someone help me with this??

mySQL not save the correct data

I’m trying to create a task app. when saving it, the server says successful

[{"taskName":"Join Group","completed":true},{"taskName":"Follow Channel","completed":true},{"taskName":"Follow Twitter","completed":false},{"taskName":"Visit Website","completed":false},{"taskName":"Visit Launchpad","completed":false}]

However, it is not saved in the database, see the follow channel task

[{"taskName": "Join Group", "completed": true}, {"taskName": "Follow Channel", "completed": false}, {"taskName": "Follow Twitter", "completed": false}, {"taskName": "Visit Website", "completed": false}, {"taskName": "Visit Launchpad", "completed": false}]

Here the UI

const handleTaskClick = (e: React.MouseEvent<HTMLAnchorElement>, taskName: string, link: string, isTaskCompleted: boolean) => {
    e.preventDefault();

    if (!isTaskCompleted && username) {
      sessionStorage.setItem('currentPage', JSON.stringify({ taskName }));

      axios.post('/api/completeTask', { username, taskName })
        .then(response => {
          console.log('Updated Task Data:', response.data);
          setTaskData(response.data);
          window.open(link, '_blank');
        })
        .catch(error => {
          console.error('Error completing task', error.response?.data || error.message);
        });
    }
  };

and here the backend

// models/Task.js

const { sequelize, DataTypes } = require("../config/mysql-sequelize");

module.exports = (sequelize, DataTypes) => {
  const Task = sequelize.define('Task', {
    username: { type: DataTypes.STRING, allowNull: false },
    tasks: {
      type: DataTypes.JSON,
      defaultValue: []
    },
    claimedAmount: { type: DataTypes.FLOAT, defaultValue: 0 }
  }, {
    timestamps: true
  });

  return Task;
};
//  routes/task.js

const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const { Task } = require('../models');

const getTasksConfig = () => {
  const filePath = path.join(__dirname, '../config/tasks.json');
  if (fs.existsSync(filePath)) {
    const fileContent = fs.readFileSync(filePath, 'utf8');
    try {
      return JSON.parse(fileContent);
    } catch (error) {
      console.error('Error parsing JSON:', error);
      return [];
    }
  } else {
    console.error('File not found:', filePath);
    return [];
  }
};


router.get('/tasksConfig', (req, res) => {
  try {
    const tasksConfig = getTasksConfig();
    res.json(tasksConfig);
  } catch (error) {
    res.status(500).json({ message: 'Error loading tasks configuration' });
  }
});

// Endpoint untuk mendapatkan data tugas pengguna
router.get('/taskData', async (req, res) => {
  const { username } = req.query;
  try {
    const taskData = await Task.findOne({ where: { username } });
    if (taskData) {
      res.json(taskData);
    } else {
      res.status(404).json({ message: 'Task data not found' });
    }
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
});

router.post('/completeTask', async (req, res) => {
  const { username, taskName } = req.body;

  console.log(`Received request to complete task: ${taskName} for user: ${username}`);

  try {
    const tasksConfig = getTasksConfig();
    const taskConfig = tasksConfig.find(t => t.taskName === taskName);

    if (!taskConfig) {
      console.log(`Task configuration not found for taskName: ${taskName}`);
      return res.status(400).json({ message: 'Invalid task name' });
    }

    let taskData = await Task.findOne({ where: { username } });

    if (!taskData) {
      console.log(`No task data found for username: ${username}. Creating new task data.`);
      taskData = new Task({
        username,
        tasks: tasksConfig.map(t => ({ taskName: t.taskName, completed: false })),
        claimedAmount: 0,
      });
    } else {
      console.log(`Existing task data found for username: ${username}`);
      const existingTaskNames = taskData.tasks.map(t => t.taskName);
      const newTasks = tasksConfig.filter(t => !existingTaskNames.includes(t.taskName));
      if (newTasks.length > 0) {
        console.log(`Adding new tasks: ${JSON.stringify(newTasks)}`);
        taskData.tasks.push(...newTasks.map(t => ({ taskName: t.taskName, completed: false })));
      }
    }

    const task = taskData.tasks.find(t => t.taskName === taskName);

    if (task) {
      if (!task.completed) {
        console.log(`Completing task: ${taskName} for user: ${username}`);
        task.completed = true;
        taskData.claimedAmount += taskConfig.reward;

        await taskData.save();
        console.log(`Task completed. Updated task data: ${JSON.stringify(taskData)}`);
        res.json(taskData);
      } else {
        console.log(`Task: ${taskName} already completed for user: ${username}`);
        res.status(400).json({ message: 'Task already completed' });
      }
    } else {
      console.log(`Task: ${taskName} not found in task data for user: ${username}`);
      res.status(400).json({ message: 'Task not found' });
    }
  } catch (error) {
    console.error('Error completing task:', error);
    res.status(500).json({ message: 'Server error' });
  }
});



router.get('/getTaskAmount', async (req, res) => {
  const { username } = req.query;

  try {
    const taskData = await Task.findOne({ where: { username } });

    if (taskData) {
      res.json({ claimedAmount: taskData.claimedAmount });
    } else {
      res.status(404).json({ message: 'User not found' });
    }
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;

What causes data not to be saved correctly to the database?

Headers error while making Discord authorization page (node.js, express, route, jsonwebtoken)

I’m making a website with dashboard for a Discord bot. Only when I’m making the authorization page with the help of JWT to make a token it keeps giving me a headers error (see below). I’ll put my code for that specific item under here. I can’t seem to find any resource for why said error pops up.

So ive tried to debug the whole code, when i do so i added console.logs to specific events happening. All of those events returned a (expected) result but only 1 event didn’t. This being adding the cookie to the browser of the individual and redirecting them towards a localhost:5173 (testing this locally before uploading to a website)

Code:

const express = require('express');
const User = require('../../models/User');
const jwt = require('jsonwebtoken');

const router = express.Router();

// GET: api.tick-it.com/auth/signin
// GET: api.tick-it.com/auth/callback

const DASHBOARD_URL = 'http://localhost:5173';

router.get('/signin', (req, res) => {
    res.redirect(
        `https://discord.com/oauth2/authorize?client_id=${process.env.DISCORD_CLIENT_ID}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fauth%2Fcallback&scope=guilds+identify`
    );
});

router.get('/callback', async (req, res) => {
    const DISCORD_ENDPOINT = 'https://discord.com/api/v10';
    const CLIENT_ID = process.env.DISCORD_CLIENT_ID;
    const CLIENT_SECRET = process.env.DISCORD_CLIENT_SECRET;
    const REDIRECT_URI = process.env.DISCORD_REDIRECT_URI;
    const DASHBOARD_URL = process.env.DASHBOARD_URL;

    const { code } = req.query;


    console.log('awaiting code to be checked');

    if (!code) {
        return res.status(400).json({
            error: 'A "code" query parameter must be present in the URL.',
        });
    }

    try {
        const oauthRes = await fetch(`${DISCORD_ENDPOINT}/oauth2/token`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                client_id: CLIENT_ID,
                client_secret: CLIENT_SECRET,
                grant_type: 'authorization_code',
                redirect_uri: REDIRECT_URI,
                code,
            }).toString(),

        });

        console.log('awaiting oauthResponse.ok');


        if (!oauthRes.ok) {
            return res.status(500).json({
                error: 'Failed to obtain OAuth token.',
            });
        }

        const oauthResJson = await oauthRes.json();

        console.log('awaiting @me');
        const userRes = await fetch(`${DISCORD_ENDPOINT}/users/@me`, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${oauthResJson.access_token}`,
            },
        });

        console.log('awaiting userResponse.ok');

        if (!userRes.ok) {
            return res.status(500).json({
                error: 'Failed to fetch user data.',
            });
        }

        const userResJson = await userRes.json();

        let user = await User.findOne({ id: userResJson.id });

        console.log('awaiting user to be found and added');

        if (!user) {
            user = new User({
                id: userResJson.id,
                username: userResJson.username,
                avatarHash: userResJson.avatar,
                accessToken: oauthResJson.access_token,
                refreshToken: oauthResJson.refresh_token,
            });
        } else {
            user.username = userResJson.username;
            user.avatarHash = userResJson.avatar;
            user.accessToken = oauthResJson.access_token;
            user.refreshToken = oauthResJson.refresh_token;
        }

        await user.save();

        const token = jwt.sign(
            {
                id: userResJson.id,
                username: userResJson.username,
                avatarHash: userResJson.avatar,
            },
            process.env.JWT_SECRET,
            { expiresIn: '7d' }
        );

        console.log('awaiting token to be added')


        return someFunction(req, res, token);
        // res.cookie('access_token', token, {
        //     httpOnly: true,
        //     secure: process.env.NODE_ENV === 'production',
        //     maxAge: 6.048e8,
        // });

        // console.log('token added to browser');

        // res.redirect(DASHBOARD_URL);

    } catch (error) {
        console.error(error);
        return res.status(500).json({
            error: 'Internal Server Error.',
        });
    }
});

router.get('/signout', (req, res) => {
    res.clearCookie('token').sendStatus(200);
});

const someFunction = (req, res, token) => {
    try {
        res.cookie('access_token', token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            maxAge: 6.048e8, // 7 days
        });

        console.log('Token added to browser');

        // Redirect the user to the dashboard
        res.redirect(DASHBOARD_URL);
    } catch (error) {
        // Error handling
        console.error('Error occurred:', error);
        if (!res.headersSent) {
            res.status(500).send('An error occurred');
        }
    }
};

module.exports = router;

Error:

Listening on port: 3001
awaiting code to be checked
awaiting oauthResponse.ok
awaiting @me
awaiting userResponse.ok
awaiting user to be found and added
awaiting token to be added
Error occurred: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:703:11)
    at ServerResponse.header (C:xampphtdocsdiscordapiapinode_modulesexpresslibresponse.js:795:10)   
    at ServerResponse.append (C:xampphtdocsdiscordapiapinode_modulesexpresslibresponse.js:756:15)   
    at res.cookie (C:xampphtdocsdiscordapiapinode_modulesexpresslibresponse.js:885:8)
    at someFunction (C:xampphtdocsdiscordapiapisrcroutesauthindex.js:140:13)
    at C:xampphtdocsdiscordapiapisrcroutesauthindex.js:115:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Getting one data attribute using another

See the DIV below. If I store the data=value attribute “?=url=homepage” in a variable, how can I use it to find the corresponding data-target attribute in the same DIV? There would be a lot of different DIVs but they will all have a unique data-target and data-value that go together. I imagine I can use javascript or jquery to accomplish this.

<header>
<div id="nav" title="Homepage" data-target="practice-page-1.php" data-value="?url=homepage">Homepage</div>
</header>

In Node.js, is there a syntax to just have an inline block which returns?

In (say) Swift, you can have an inline block with a return, anywhere you like in code, for example:

let x = 3
let y = 4
let z = {
  blah
  blah
  blah
  return blah blah
}()
let p = 12
let q = 13

or say:

ra.append( // (Swift equivalent of push)
   {
        blah
        blah
        return blah
   }()
)

The best I can do on Node.js (this is server side only, if it matters) is:

ra.push(
    (() => {
        x = 3
        y = x * 12
        return y
    })()
)

Is there a better way?

Select cursor define position

Spin wheel

Hello, how can I set the cursor position to retrieve the number in the wheel segments?

<div class="wheel-container">
            <div class="spinBtn">Tourner</div>
            <div class="wheel">
                <span style="--i:0;"></span>
                <span style="--i:1;"></span>
                <span style="--i:2;"></span>
                <span style="--i:3;"></span>
                <span style="--i:4;"></span>
                <span style="--i:5;"></span>
                <span style="--i:6;"></span>
                <span style="--i:7;"></span>
                <span style="--i:8;"></span>
                <span style="--i:9;"></span>
                <span style="--i:10;"></span>
                <span style="--i:11;"></span>
                <span style="--i:12;"></span>
                <span style="--i:13;"></span>
                <span style="--i:14;"></span>
                <span style="--i:15;"></span>
                <span style="--i:16;"></span>
                <span style="--i:17;"></span>
                <span style="--i:18;"></span>
                <span style="--i:19;"></span>
                <span style="--i:20;"></span>
                <span style="--i:21;"></span>
                <span style="--i:22;"></span>
                <span style="--i:23;"></span>
                <span style="--i:24;"></span>
                <span style="--i:25;"></span>
                <span style="--i:26;"></span>
                <span style="--i:27;"></span>
                <span style="--i:28;"></span>
                <span style="--i:29;"></span>
                <span style="--i:30;"></span>
                <span style="--i:31;"></span>
                <span style="--i:32;"></span>
                <span style="--i:33;"></span>
                <span style="--i:34;"></span>
                <span style="--i:35;"></span>
                <span style="--i:36;"></span>
                <span style="--i:37;"></span>
                <span style="--i:38;"></span>
                <span style="--i:39;"></span>
                <span style="--i:40;"></span>
                <span style="--i:41;"></span>
                <span style="--i:42;"></span>
                <span style="--i:43;"></span>
                <span style="--i:44;"></span>
                <span style="--i:45;"></span>
                <span style="--i:46;"></span>
                <span style="--i:47;"></span>
                <span style="--i:48;"></span>
                <span style="--i:49;"></span>
                <span style="--i:50;"></span>
                <span style="--i:51;"></span>
                <span style="--i:52;"></span>
                <span style="--i:53;"></span>
                <span style="--i:54;"></span>
                <span style="--i:55;"></span>
                <span style="--i:56;"></span>
                <span style="--i:57;"></span>
                <span style="--i:58;"></span>
                <span style="--i:59;"></span>
                <span style="--i:60;"></span>
                <span style="--i:61;"></span>
                <div class="number">
                    <b id="0" style="--i:0;">0</b>
                    <b id="1" style="--i:1;">1</b>
                    <b id="2" style="--i:2;">2</b>
                    <b id="3" style="--i:3;">3</b>
                    <b id="4" style="--i:4;">4</b>
                    <b id="5" style="--i:5;">5</b>
                    <b id="6" style="--i:6;">6</b>
                    <b id="7" style="--i:7;">7</b>
                    <b id="8" style="--i:8;">8</b>
                    <b id="9" style="--i:9;">9</b>
                    <b id="10" style="--i:10;">10</b>
                    <b id="11" style="--i:11;">11</b>
                    <b id="12" style="--i:12;">12</b>
                    <b id="13" style="--i:13;">13</b>
                    <b id="14" style="--i:14;">14</b>
                    <b id="15" style="--i:15;">15</b>
                    <b id="16" style="--i:16;">16</b>
                    <b id="17" style="--i:17;">17</b>
                    <b id="18" style="--i:18;">18</b>
                    <b id="19" style="--i:19;">19</b>
                    <b id="20" style="--i:20;">20</b>
                    <b id="21" style="--i:21;">21</b>
                    <b id="22" style="--i:22;">22</b>
                    <b id="23" style="--i:23;">23</b>
                    <b id="24" style="--i:24;">24</b>
                    <b id="25" style="--i:25;">25</b>
                    <b id="26" style="--i:26;">26</b>
                    <b id="27" style="--i:27;">27</b>
                    <b id="28" style="--i:28;">28</b>
                    <b id="29" style="--i:29;">29</b>
                    <b id="30" style="--i:30;">30</b>
                    <b id="31" style="--i:31;">31</b>
                    <b id="32" style="--i:32;">32</b>
                    <b id="33" style="--i:33;">33</b>
                    <b id="34" style="--i:34;">34</b>
                    <b id="35" style="--i:35;">35</b>
                    <b id="36" style="--i:36;">36</b>
                    <b id="37" style="--i:37;">37</b>
                    <b id="38" style="--i:38;">38</b>
                    <b id="39" style="--i:39;">39</b>
                    <b id="40" style="--i:40;">40</b>
                    <b id="41" style="--i:41;">41</b>
                    <b id="42" style="--i:42;">42</b>
                    <b id="43" style="--i:43;">43</b>
                    <b id="44" style="--i:44;">44</b>
                    <b id="45" style="--i:45;">45</b>
                    <b id="46" style="--i:46;">46</b>
                    <b id="47" style="--i:47;">47</b>
                    <b id="48" style="--i:48;">48</b>
                    <b id="49" style="--i:49;">49</b>
                    <b id="50" style="--i:50;">50</b>
                    <b id="51" style="--i:51;">51</b>
                    <b id="52" style="--i:52;">52</b>
                    <b id="53" style="--i:53;">53</b>
                    <b id="54" style="--i:54;">54</b>
                    <b id="55" style="--i:55;">55</b>
                    <b id="56" style="--i:56;">56</b>
                    <b id="57" style="--i:57;">57</b>
                    <b id="58" style="--i:58;">58</b>
                    <b id="59" style="--i:59;">59</b>
                    <b id="60" style="--i:60;">60</b>
                    <b id="61" style="--i:61;">61</b>
                </div>
            </div>
        </div>

Can you help me do this?

I tried to retrieve the id of the b tags to do it but I can’t do it

I created this code like this to set the number of segments of the wheel with

span

tags and display the numbers in the segments with

b

tags

@justnut:
This is a part of my js code i use for turn this wheel

    const spinDuration = 3600; // Durée de la rotation en secondes
let wheel = document.querySelector('.wheel');
let spinBtn = document.querySelector('.spinBtn');
let value = Math.ceil(Math.random() * -3600);
spinBtn.addEventListener("click", function() {
    const spanIndex = Math.floor(Math.random() * images.length); // Obtenir un index aléatoire
    wheel.style.transform = `rotate(${value}deg)`;
    value += Math.ceil(Math.random() * 3600);

How to retrieve fetch requests through chrome extension

How can I retrieve the request that are being send and received from the server.
For example, when I look at the chrome devtool, I can see under network all the fetch/XHR requests being send and received.

What I want to be able to do is through my chrome extension, I want my inject.js to print these on the console but I can’t seem to be able to get a handle on it. Anyone knows how t have a simple script to catch request and print it on the console?

My manifest contains the following:

"host_permissions": [
    "https://*.abc.com/path/*"
  ],
  "content_scripts": [
    {
      "matches": ["https://*.abc/path/*"],
      "js": ["inject.js"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["inject.js"],
      "matches": ["<all_urls>"]
    }
  ],

my inject.js is this

(function() {
  // Intercept fetch requests
  const originalFetch = window.fetch;
  window.fetch = function(...args) {
    console.log('Intercepted fetch request:', args);
    
    return originalFetch(...args).then(response => {
      const clonedResponse = response.clone();
      
      // Read response body
      clonedResponse.text().then(text => {
        console.log('Fetch response text:', text);
     });
      
      return response;
    }).catch(error => {
      console.error('Fetch error:', error);
    });
  };

  // Intercept XMLHttpRequest
  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url, ...rest) {
    this._url = url;
    this.addEventListener('load', function() {
      console.log('Intercepted XMLHttpRequest:', {
        method: method,
        url: this._url,
        responseText: this.responseText
      });
    });

    originalOpen.apply(this, [method, url, ...rest]);
  };

  XMLHttpRequest.prototype.send = function(...args) {
    console.log('Intercepted XMLHttpRequest send:', args);
    originalSend.apply(this, args);
  };

})();

Many thanks in advance

Cannot find module error in Node.js: Module not found due to incorrect path

I’m working on a Node.js project and I’ve encountered a Cannot find module error when trying to require a module. The error looks something like this:
Error: Cannot find module ”

I tried requiring the module in main.js and execute the node file with the following line of code

1.const myModule = require('myModule');
2.node index.js

1.I expected this to import the module without any issues since I assumed Node.js would locate it automatically. However, it threw a Cannot find module error instead. I checked that the file exists and is named mymodule.js, but it is in a different folder (modules).
2.Error occurs when we write wrong filepath and wrong file name

Get submitted button’s name in Sveltekit actions

I’ve got a form with 2 buttons:

<form method="POST" class="pt-10">
<div class="flex flex-row pt-10">
                <button type="submit" name="save-and-exit" class="btn btn-primary btn-lg">{ mode == "new" ? "Save and Exit" : "Update and Exit" }</button>
            </div>

            <div class="flex flex-row pt-10">
                <button type="submit" name="add-tracks" class="btn btn-primary btn-lg">{ "-> Tracks" }</button>
            </div>
</form>

Omitting the fields in form for simplicity.

My action looks like this:

export const actions = {
    default: async ({ request, fetch }) => {

        // create API instance
        const recordAPI = new RecordAPI(fetch);

        // retrieve the data from the form
        const data = Object.fromEntries(await request.formData());

        // validate data and create DTO
        const record = recordDTO(data);

        // if errors returned from building the DTO (validation errors) then return the object.
        if (record?.errors && !emptyObject(record.errors)) {
            return {
                "data": record.data,
                "errors": record.errors,
            };
        }

        // save the data
        const response = await recordAPI.post(record);

        if (response.status == 200) {
            throw redirect(302, '/records')
        }

        return {
            data: record,
            "errors": response.errors,
        }
}

In the action function, is there a way to know which of the 2 buttons was the one that submitted the form? I need to know this since the flow is gonna be different depending on that.

One solution I can think of is updating the form to something like this:

<form method="POST" bind:this={formElement}>

then manually append the name of the button to the form and trigger formElement.requestSubmit(), but I was wondering if there’s a way to do it directly in the action, I believe it looks more ‘elegant’.

Thanks.