Livewire component JS script Uncaught SyntaxError: Unexpected token

I am using livewire component and in component blade file I am using script,

@assets
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
@endassets

@script
    <script>
        var options = {
            series: [],
            legend: {
                show: false
            },
            chart: {
                height: '650px',
                type: 'treemap'
            },
            dataLabels: {
                enabled: true,
                style: {
                    fontSize: '12px',
                },
                formatter: function(text, op) {
                    return [text, op.value]
                },
                offsetY: -4
            },
            plotOptions: {
                treemap: {
                    enableShades: true,
                    shadeIntensity: 0.5,
                    reverseNegativeShade: true,
                    colorScale: {
                        ranges: [{
                                from: -6,
                                to: 0,
                                color: '#CD363A'
                            },
                            {
                                from: 0.001,
                                to: 6,
                                color: '#52B12C'
                            }
                        ]
                    }
                }
            }
        };

        var chart = new ApexCharts(document.querySelector("#chart"), options);
        chart.render();

        $wire.on('dataUpdated', (data) => {
            const dataArray = data[0];
            // Map the data to format it properly
            const mappedData = dataArray.map(item => ({
                x: item.asset_symbol,
                y: item.pchange
            }));

            mappedData.sort((a, b) => b.y - a.y);

            chart.updateSeries([{
                data: mappedData
            }]);

            console.log(dataArray);
            console.log('updated');
        });
    </script>
@endscript


But when the page loads, it throws an error

livewire.js?id=5d8beb2e:1243  **Uncaught SyntaxError: Unexpected token 'var'**
    at new AsyncFunction (<anonymous>)
    at safeAsyncFunction (livewire.js?id=5d8beb2e:1243:21)
    at generateFunctionFromString (livewire.js?id=5d8beb2e:1253:16)
    at generateEvaluatorFromString (livewire.js?id=5d8beb2e:1258:16)
    at normalEvaluator (livewire.js?id=5d8beb2e:1223:111)
    at evaluateLater (livewire.js?id=5d8beb2e:1213:12)
    at Object.evaluate (livewire.js?id=5d8beb2e:1209:5)
    at livewire.js?id=5d8beb2e:8592:28
    at Object.dontAutoEvaluateFunctions (livewire.js?id=5d8beb2e:1203:18)
    at livewire.js?id=5d8beb2e:8591:26

If I move var options.... after $wire.on function then it loads correctly,

Why component script does not recognise var or const?

status for all attendance entries (even in different dates) in database keeps updating when all checkboxes are checked

i was testing for an attendance website, logging attendance on different dates (manually changing the date on my device) i have a status column 1 for present and 0 for absent. when i log an attendance where some are absent, the status column on that date are reflected correctly but when I log an attendance where all are present, the status column values on all dates (including the ones with ‘0’) are all changed to ‘1’. below is the code for the save

if(isset($_POST['save'])){
    
    $studentNo=$_POST['studentNo'];
    $check=$_POST['check'];
    $N = count($studentNo);
    $status = "";

  $qurty=mysqli_query($conn,"select * from tblattendance where subject = '$id' and date = '$dateTaken' and status = '1'");
  $count = mysqli_num_rows($qurty);

  if($count > 0){

      $statusMsg = "<div class='alert alert-danger' style='margin-right:700px;'>Attendance has been taken for today!<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button></div>";

  }else
    {
      for($i = 0; $i < $N; $i++)
        {
         $studentNo[$i]; 
            if(isset($check[$i]))
                {
                 $qquery=mysqli_query($conn,"update tblattendance set status='1' where studentNo= '$check[$i]'");

                      if ($qquery) {

                          $statusMsg = "<div class='alert alert-success'  style='margin-right:700px;'>Attendance Taken Successfully!<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button></div>";
                      }
                      else
                      {
                          $statusMsg = "<div class='alert alert-danger' style='margin-right:700px;'>An error Occurred!</div>";
                      }
                  
                }
          }
      }
}

i’m wondering why all the values in all logged dates in the db are changed to ‘1’ and if there is a way to fix this. if you need anything else, please dont hesitate to let me know and I really appreciate all the help i can get. thank you in advance!

On iOS, the keyboard does not offer a 6-character SMS code

I’m developing a mobile application in React Native. The application has the <TextInput/> for entering SMS codes:

const [pinCode, setPinCode] = useState('');
const pinCodeRef = useRef();

// crutch so that the user's keyboard opens automatically
useEffect(() => {
  const timeout = setTimeout(() => {
    pinCodeRef.current.focus();
  }, 400);
  return () => clearTimeout(timeout);

}, []);

...

<TextInput 
  placeholder="Enter pin-cpde" 
  placeholderTextColor={commonStyles.colors.label}
  value={pinCode}
  onChangeText={val => setPinCode(val)}
  maxLength={6}
  ref={pinCodeRef}
  keyboardType="number-pad"
  autoComplete="sms-otp"
  textContentType="oneTimeCode"
/>

I use properties keyboardType="number-pad" autoComplete="sms-otp" textContentType="oneTimeCode" to have the keyboard prompt the user for an SMS code.

The problem is that 6-digit codes on IOS are not prompted, while 4-digit codes work correctly. On Android everything works correctly.

About app:

System:
    OS: macOS 13.4
    CPU: (8) arm64 Apple M1 Pro
    Memory: 141.94 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 16.18.0 - ~/.nvm/versions/node/v16.18.0/bin/node
    Yarn: 1.22.19 - /opt/homebrew/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v16.18.0/bin/npm
    Watchman: Not Found
  Managers:
    CocoaPods: 1.11.2 - /Users/alexander/.rvm/rubies/ruby-2.7.4/bin/pod
  SDKs:
    iOS SDK:
      Platforms: DriverKit 22.2, iOS 16.2, macOS 13.1, tvOS 16.1, watchOS 9.1
    Android SDK: Not Found
  IDEs:
    Android Studio: 2022.2 AI-222.4459.24.2221.10121639
    Xcode: 14.2/14C18 - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.16.1 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.2 => 17.0.2 
    react-native: 0.67.4 => 0.67.4 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

Libraries (for example react-native-otp-auto-fill) did not cope with the code hint (on IOS and ob Android). Only the properties mentioned above helped me.

RSpec Capybara throwing Selenium error when trying to click a button with browser confirm

I’m running into an error with an end-to-end Capybara spec in my Rails application.

Here is the relevant part of my view:

#show.html.erb
...
<%= button_to 'Cancel',
  cancel_subscription_path,
  class: 'button button--danger',
  data: {
    turbo_confirm: 'Are you sure you want to cancel?',
    turbo_method: 'post'
  }
%>
<div id="cancel_message"></div>
...
# cancel_subscription_spec.rb

require 'rails_helper'

RSpec.describe 'CancelSubscriptions', js: true do
  it 'cancels an active subscription' do
    email = sign_up_and_subscribe

    visit subscription_path

    accept_confirm do
      click_button 'Cancel'
    end

    subscription = User.find_by(email:).current_subscription

    expect(subscription.cancelled?).to be(true)
  end
end

sign_up_and_subscribe is just a simple helper method that signs up to the application and fills in the Stripe form to create a subscription – it works in other tests and I also see the subscription created in the Stripe dashboard, this isn’t the issue.

When the spec reaches visit subscription_path and attempts to click the cancel button, I get the following error:

Selenium::WebDriver::Error::UnexpectedAlertOpenError:  
  unexpected alert open: {Alert text : }
    (Session info: chrome-headless-shell=123.0.6312.87)

I figured I was misusing the accept_confirm method, but from what I found in the documentation, this is the correct usage.

What I found strange was that commenting out the accept_confirm in the spec and the turbo_confirm in the view didn’t actually change the error message. Is Capybara caching the page in between test runs?

I would consider changing the behaviour to make the spec pass at this point, I prefer to have a well-tested user flow even if that means a small change in the user experience, but I can’t even do that, the issue remains the same.

In case it’s helpful, the relevant part of the rails_helper.rb is:

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new app, browser: :chrome,
                                      options: Selenium::WebDriver::Chrome::Options.new(args: %w[headless disable-gpu])
end

Capybara.javascript_driver = :chrome

I can post the rest if it might be useful, but it’s mostly unrelated as far as I can see.

My cancel action in the controller looks like this:

def cancel
  @subscription = current_user.current_subscription
  SubscriptionCanceller.new(subscription_id: @subscription.provider_id).call
rescue SubscriptionCancellationError => _e
  render :cancellation_error
end

where I have turbo_stream views for cancellation_error and cancel itself, both of which work in the browser when I test them manually.

Just in case that affects it, here is the cancel.turbo_stream.erb

<%= turbo_stream.replace 'cancel_message' do %>
  <div>We are cancelling your subscription.</div>
<% end %>

If there is any further detail/code required, let me know and I’ll post it.

Used AI to generate an Adobe Illustrator v28.3 script that groups the contents of each individual artboard. Can’t get it to work

What would be the best way to solve the problem of wanting to ‘auto group’ all artboards?

Opposed to dragging a selection box of each artboard, then hitting CMD+G, each page has 8 artboards and I have probably 80-150 pages to get through.

To those proficient in javascript, does this code resemble something workable or should I pack it in?

var doc = app.activeDocument;

for (var i = 0; i < doc.artboards.length; i++) {
    doc.artboards.setActiveArtboardIndex(i);
    var artboard = doc.artboards[i];
    var itemsOnArtboard = [];

    for (var j = 0; j < doc.pageItems.length; j++) {
        var item = doc.pageItems[j];
        if (artboard.artboardRect.toString() == item.visibleBounds.toString()) {
            itemsOnArtboard.push(item);
        }
    }

    if (itemsOnArtboard.length > 1) {
        var group = doc.groupItems.add();
        for (var k = 0; k < itemsOnArtboard.length; k++) {
            itemsOnArtboard[k].moveToEnd(group);
        }
    }
}

I was expecting Illustrator to cycle through each art board and grouping the contents from each board until it finally reached the last board.

The code seemed to take, beach ball spun for a bit, but no result.

JavaScript svg scale issue with matter.js

I’m developing a Javascript animation using matter.js. Here is the link:

https://codepen.io/Sergio-Escalona/pen/VwNrwbw

document.addEventListener("DOMContentLoaded", function () {
    // Basic setup
    let Engine = Matter.Engine,
        World = Matter.World,
        Bodies = Matter.Bodies,
        Body = Matter.Body;

    let engine = Engine.create();
    engine.world.gravity.y = 0; // No gravity for a space-like effect

    let render = Matter.Render.create({
        element: document.body,
        engine: engine,
        options: {
            width: window.innerWidth,
            height: window.innerHeight,
            background: 'transparent',
            wireframes: false // for sprite rendering
        }
    });

    // Create static walls
    let thickness = 50; // Ensures ducks don't escape through fast movements
    let wallOptions = { isStatic: true, restitution: 1.0 }; // Perfectly elastic collisions
    let ground = Bodies.rectangle(window.innerWidth / 2, window.innerHeight + thickness / 2, window.innerWidth, thickness, wallOptions);
    let leftWall = Bodies.rectangle(-thickness / 2, window.innerHeight / 2, thickness, window.innerHeight, wallOptions);
    let rightWall = Bodies.rectangle(window.innerWidth + thickness / 2, window.innerHeight / 2, thickness, window.innerHeight, wallOptions);
    let topWall = Bodies.rectangle(window.innerWidth / 2, -thickness / 2, window.innerWidth, thickness, wallOptions);

    World.add(engine.world, [ground, leftWall, rightWall, topWall]);

    // Function to add a new duck with random selection for black duck
    function addDuck() {
        let safeMargin = 100; // A margin to avoid spawning too close to the edge
        let radius = 25;
        // Randomly choose the texture for the duck
        let textureUrl = Math.random() < 0.9 ? 
            'https://assets.codepen.io/12210161/duckling-svgrepo-com.svg' : 
            'https://assets.codepen.io/12210161/duckling-svgrepo-com-bk.svg';
        let duck = Bodies.circle(Math.random() * (window.innerWidth - 2 * safeMargin) + safeMargin, Math.random() * (window.innerHeight - 2 * safeMargin) + safeMargin, radius, {
            restitution: 0.9,
            friction: 0.0,
            frictionAir: 0.0,
            density: 0.001,
            render: {
                sprite: {
                    texture: textureUrl,
                    xScale: 0.1,
                    yScale: 0.1
                }
            }
        });

        // Apply an initial force to ensure movement
        Body.applyForce(duck, {x: duck.position.x, y: duck.position.y}, {x: (Math.random() - 0.5) * 0.05, y: (Math.random() - 0.5) * 0.05});
        World.add(engine.world, duck);
    }

    document.getElementById("oneMoreBtn").addEventListener("click", addDuck);

    // Start the engine and renderer
    Engine.run(engine);
    Matter.Render.run(render);

    // Initially add a duck to start with
    addDuck();
});

I don’t know why black ducks are smaller than the regular ones. The svg files dimensions (px) are exactly the same and I can’t find where is the problem.

Can anyone help me to solve it?

Thanks in advance!!!

I’ve checked the svg files and both are exactly the same size. About the Javascript code I can’t find anything beyond the render scale but I think it shouldn’t be the problem.

NPM packages installation error – it’s not only about vite it’s same problem during installing any packages

node:9720) [DEP0170] DeprecationWarning: The URL http://proxy.example.com:port is invalid. Future versions of Node.js will throw an error.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:5040) [DEP0170] DeprecationWarning: The URL http://proxy.example.com:port is invalid. Future versions of Node.js will throw an error.
(Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! code ERR_INVALID_URL
npm ERR! Invalid URL

Sepolia test network ID

THIS IS MY TRUFFLE-CONFIG.JS

require("babel-register");
const HDWalletProvider = require("truffle-hdwallet-provider");
require("dotenv").config();
module.exports = {
    networks: {
        Sepolia: {
            provider: function() {
                return new HDWalletProvider(
                    process.env.MNEMONIC,
                    process.env.PROJECT_ENDPOINT,
                    address_index=0,
                    num_addresses=2
                );
            },
            network_id: 11155111    ,
             gas: 4500000,
             gasPrice: 10000000000,
        },
        development: {
            host: process.env.LOCAL_ENDPOINT.split(":")[1].slice(2),
            port: process.env.LOCAL_ENDPOINT.split(":")[2],
            network_id: "*",
        },
        compilers: {
            solc: {
                version: "^0.4.24",
            },
        },
    },
};

I AM UNABLE TO GET THE NETWORK ID FOR SEPOLIA TEST NETWORK
BELOW IS THE LINK OF THE ERROR COMING-
[1]: https://i.stack.imgur.com/HPl09.png

Next.js not generating a project

I am trying to build a project and in the tutorial they tell me to start with this

npx create-next-app –e with-tailwindcss amazon-scraper

But when it completes building I only have a readme.md and a gitignore folder.

Even though I am a beginner I already worked with npx create-next app and it worked alright.

It is really frustating since I am trying to start a new project and I am stuck right at the beginning. Thanks for your help.

This is what I should get

Getting an error in Socket.io wordle project

I was creating a multiplayer wordle and am getting this error:
Uncaught TypeError: Failed to resolve module specifier "socket.io-client". Relative references must start with either "/", "./", or "../".
The code is running fine when i run the client locally but not when i host the client side on netlify or github.
The following is the server side code:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {origin: ["https://h4r5h-10.github.io/private-test/"],}
});
const PORT = process.env.PORT || 3000;
var tempArr = [];
console.log(tempArr)
var index; var correctWord;
io.on('connection', socket => {
    // console.log(socket.id);
    socket.on("disconnect", ()=>{
      const ind2 = tempArr.findIndex((obj) => obj.p1 == socket.id || obj.p2 == socket.id);
      if(ind2 != -1){
        tempArr.splice(ind2,1);
      }
    })
    // io.emit("sendword", correctWord);
    socket.on("submitguess", (arr, room) =>{
        socket.to(room).emit("sendtiles", arr);
    })
    socket.on("join-room", room =>{
        const ind1 = tempArr.findIndex((obj)=> obj.room == room);
        const ind2 = tempArr.findIndex((obj)=> obj.p1 == socket.id);
        // const ind3 = tempArr.findIndex((obj)=> obj.p2 == socket.id);
        if(ind1 !== -1 && tempArr[ind1].p1 && tempArr[ind1].p2) {
            socket.emit("room-full")
            return
        }
        socket.join(room);
        var count = 0;
        if(ind1 == -1)
        {
            index = Math.floor(Math.random() * dictionary.length);
            correctWord = dictionary[index];
            tempArr.push({room: room, p1: socket.id, p2: null, correctWord: correctWord});
            socket.emit("sendword", correctWord);
            count = 1;
        }
      else if(ind2 !== -1){
            count = 1;
        }
        else if(ind1 !== -1 && ind2 == -1){
            tempArr[ind1].p2 = socket.id;
            socket.emit("sendword", correctWord);
        }
        io.to(room).emit("waiting-room", count);
      console.log(tempArr);
    })
    socket.on("socket-win", (id, room) => {
        const ind2 = tempArr.findIndex((obj) => obj.p1 == id || obj.p2 == id);
        socket.to(room).emit("shut-down", ind2);
        tempArr.splice(ind2,1);
    })
    socket.on("socket-exhaust", (id, room) => {
        const ind2 = tempArr.findIndex((obj) => obj.p1 == id || obj.p2 == id);
        socket.to(room).emit("exhaust-out", ind2);
        tempArr.splice(ind2,1);
    })
})

server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

The following is client side code:
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Wordle Multiplayer</title>
    <link rel="stylesheet" href="styles.css" />
    <script type="module" src="index.js" defer></script>
    <!-- <script  src="/socket.io/socket.io.js"></script>   -->
    <script type="/module" src="https://cdn.socket.io/4.7.5/socket.io.esm.min.js"></script>  
  </head>
  <body>
    <div class="restart-container hide" data-restart-con>
      <div class="btn-container">
        <button class="btn" onclick="window.location.reload()">New Game</button>
        <a href="../../index.html"><button class="btn">Menu</button></a>
      <button class="btn close" onclick="closeRestart()">Close</button>
      </div>
    </div>
    <div class="join-container">
      <div class="join-btn-container">
        <input type="text" class="room-code" placeholder="Enter Room Name">
        <button class="btn play">Play Game</button>
      </div>
    </div>
    <div class="alert-container" data-alert-con></div>
    <div class="grid-container">
      //code 
    </div>
  </body>
</html>

index.js

import io from "socket.io-client";

var room = "";
var arr = [];
var correctWord = "";
const guessGridYou = document.querySelector(".grid.you");
const guessGridOpp = document.querySelector(".grid.opponent");
const keyboard = document.querySelector(".keyboard");

const socket = io("https://wordle-server-application.glitch.me/", {headers: { "user-agent": "Google Chrome"}})

I tried all the past answers but they arent working.

Accessing displayed text of an HTML element with JavaScript

Given a

<div id="e83v8" style="width: 86px; background-color: red; font-size: 10px; overflow-wrap: word-break; hyphens: auto;">This is a text that is long enough to cause a line break if set so. By using words like "incomprehensibilities", we can demonstrate word breaks.</div>

I would like to access the formatted text with hyphenations with JavaScript to get a string similar to "This is a text that is long enough to cause a line break if set so. By using words like "incomprehensibilit-ies", we can demon-strate word breaks.". Is this possible?

The use case is that I need a way to break and hyphenate text in a <text> element of an SVG by only using SVG elements.

What I’m I doing wrong with my custom video controls

I am trying to create custom video controls for my react native app but it seems like I am missing something. Currently only the pause/play functionality work. The fast forward/ rewinding and slider don’t work. Here is the code for the pause and play functionality that works.

const togglePlayPause = async () => {
        if (videoRef.current) {
          if (isPlaying) {
            await videoRef.current.pauseAsync();
          } else {
            await videoRef.current.playAsync();
          }
          setIsPlaying(!isPlaying);
        }
      };

<View style={styles.controls}>
            <TouchableOpacity onPress={togglePlayPause} style={styles.controlButton}>
                {isPlaying?
                <FontAwesome5 name="pause" size={30} color="white" />
                :
                <FontAwesome5 name="play" size={30} color="white" />
                }
            </TouchableOpacity>
      </View>

I think I did the right thing but it’s not working so probably not. Could someone tell me what I am doing wrong? This is the rest of the code including the pause and play functionally I mentioned earlier

import { View, Text,Dimensions, ImageBackground,StyleSheet, StatusBar, FlatList,Image, TouchableOpacity } from 'react-native'
import { TapGestureHandler, State } from 'react-native-gesture-handler';
import { FontAwesome5 } from '@expo/vector-icons';
import Slider from '@react-native-community/slider';
import React,{useState,useEffect,useRef} from 'react'
import EchoIcon from './Echo';
import ThumbsDownIcon from './ThumbsDown';
import ThumbsUpIcon from './ThumbsUp';
import { Video,ResizeMode } from 'expo-av';
import { supabase } from '../../../../supabase1';
import CommentThumbsUp from '../../../../animations/CommentThumbsUp';
import CommentThumbsDown from '../../../../animations/CommentThumbsDown';

export default function ViewPostMedia({navigation,route}) {
    const screenWidth = Dimensions.get('window').width;
    const SCREEN_HEIGHT = (Dimensions.get('window').height)
    const {media} =route.params;
    const {postID} = route.params;
    const {initialLikes} = route.params
    const {initialDislikes} = route.params
    const {initialEchoes} = route.params
    const {mediaType} = route.params
    const [Comments, setComments] = useState([])
    const videoRef = useRef(null);
    const [isPlaying, setIsPlaying] = useState(false);
    const [sliderValue, setSliderValue] = useState(0);
    const [videoDuration, setVideoDuration] = useState(0);
    const [sliderBeingDragged, setSliderBeingDragged] = useState(false);
    const [doubleTapRight, setDoubleTapRight] = useState(false);
    const [doubleTapLeft, setDoubleTapLeft] = useState(false);

    
    

    useEffect(() => {
      const getVideoDuration = async () => {
        if (videoRef.current) {
          const { durationMillis } = await videoRef.current.getStatusAsync();
          console.log('Video duration:', durationMillis / 1000);
          setVideoDuration(durationMillis / 1000); 
        }
      };

      getVideoDuration();
    }, [videoRef.current]);

    // Update slider position based on video progress
    useEffect(() => {
      const updateSliderPosition = () => {
        if (videoRef.current) {
          videoRef.current.getStatusAsync().then((status) => {
            const { positionMillis, durationMillis } = status;
            const currentPosition = positionMillis / 1000; 
            const progress = currentPosition / (durationMillis / 1000);
            setSliderValue(progress);
          });
        }
      };

      const intervalId = setInterval(updateSliderPosition, 1000); // Update every second

      return () => clearInterval(intervalId); // Clean up interval
    }, [videoRef.current]);

    const onSlidingStart = () => {
      setSliderBeingDragged(true);
    };
    
    const onSlidingComplete = async (value) => {
      setSliderBeingDragged(false);
      setSliderValue(value);
      const newPosition = value * videoDuration;
      await videoRef.current.setPositionAsync(newPosition);
    };
    
    

    // Function to handle slider value change
    const onSliderValueChange = (value) => {
      setSliderValue(value);
    };
    


    const togglePlayPause = async () => {
        if (videoRef.current) {
          if (isPlaying) {
            await videoRef.current.pauseAsync();
          } else {
            await videoRef.current.playAsync();
          }
          setIsPlaying(!isPlaying);
        }
      };
      useEffect(() => {
        const handleDoubleTap = async () => {
          if (doubleTapRight) {
            // Move video 5 seconds ahead
            const newPosition = Math.min(videoDuration, await videoRef.current.getStatusAsync().then((status) => {
              const { positionMillis } = status;
              return (positionMillis / 1000) + 5; // Convert to seconds
              
            }));
            console.log("New position to the right:",newPosition)
            await videoRef.current.setPositionAsync(newPosition);
            console.log('Position set successfully.',newPosition); 
            await videoRef.current.playAsync(); 
            console.log('Video playback started.'); 
          } else if (doubleTapLeft) {
            // Move video 5 seconds behind
            const newPosition = Math.max(0, await videoRef.current.getStatusAsync().then((status) => {
              const { positionMillis } = status;
              return (positionMillis / 1000) - 5; // Convert to seconds
            }));
            console.log("New position to the left:",newPosition)
            await videoRef.current.setPositionAsync(newPosition);
            console.log('Position set successfully.',newPosition); 
            await videoRef.current.playAsync(); 
            console.log('Video playback started.'); 
          }
        };
    
        handleDoubleTap();
      }, [doubleTapRight, doubleTapLeft]);


    useEffect(() => {
        fetchComments();
      }, [postID]);

      const formatTimestamp = (timestamp) => {
        const currentDate = new Date();
        const postDate = new Date(timestamp);
    
        const timeDifference = currentDate - postDate;
        const secondsDifference = Math.floor(timeDifference / 1000);
        const minutesDifference = Math.floor(secondsDifference / 60);
        const hoursDifference = Math.floor(minutesDifference / 60);
        const daysDifference = Math.floor(hoursDifference / 24);
    
        if (secondsDifference < 60) {
          return `${secondsDifference}s ago`;
        } else if (minutesDifference < 60) {
          return `${minutesDifference}m ago`;
        } else if (hoursDifference < 24) {
          return `${hoursDifference}h ago`;
        } else {
          return `${daysDifference}d ago`;
        }
      };

    const fetchComments = async () => {
        try {
          const { data: commentsData, error: commentsError } = await supabase
            .from('comments')
            .select('*')
            .eq('post_id', postID); 

          if (commentsError) {
            console.error('Error fetching comments:', commentsError);
            return;
          }
    
          // Fetch user details for each comment
        const commentsWithUserDetails = await Promise.all(
          commentsData.map(async (comment) => {
            const { data: userData, error: userError } = await supabase
              .from('profiles')
              .select('*')
              .eq('id', comment.user_id)
              .single();
    
            if (userError) {
              console.error(`Error fetching user details for comment ${comment.comment_id}:`, userError);
              return comment;
            }
    
            return {
              ...comment,
              userDetails: userData || {},
            };
          })
        );
              setComments(commentsWithUserDetails || []);
        } catch (error) {
          console.error('Error in fetchComments function:', error);
        } 
      };

      const renderItem = ({ item: comment }) => (
        <View style={{borderTopWidth:1, borderTopColor:'#B3B3B3'}}>
          <View style={styles.commentcontainer}>
            <View style={styles.profileanduser}>
              <View style={styles.postprofilepicturecontainer}>
                <Image style={styles.postprofilepicture} source={{ uri: comment.userDetails?.profile_picture_url }} />
              </View>
              <Text style={styles.usernameposttext}>@{comment.userDetails?.username}</Text>
              <Text style={styles.timetext}>{formatTimestamp(comment.created_at)}</Text>
            </View>
            <View style={styles.commentviewtextcontainer}>
              <Text style={styles.commentsviewtext}>{comment.text}</Text>
              <View style={styles.commentreactioncontainer}>
              <CommentThumbsUp postId={comment.comment_id} initialLikes={comment.likes} />
              <Text style={styles.userpostreactionstext}>{comment.likes}</Text>
              <CommentThumbsDown postID={comment.comment_id} initialDislikes={comment.dislikes} />
              <Text style={styles.userpostreactionstext}>{comment.dislikes}</Text>
              </View>
            </View>
          </View>
        </View>
    
      );
    

  return (
    <View >
     <StatusBar backgroundColor={'transparent'}/>
    { mediaType === 'image' ?
       
      <ImageBackground style={{width:screenWidth,height:SCREEN_HEIGHT}} source={{uri:media}}>
      <View style={styles.bottomTab}>
        <ThumbsUpIcon postID={postID} initialLikes={initialLikes} />
        <ThumbsDownIcon postID={postID} initialDislikes={initialDislikes} />
        <EchoIcon postID={postID} initialEchoes={initialEchoes}/>
      </View>
      </ImageBackground>
:
    <View>
        <View  style={styles.mediacontainer}>
        <Video
        ref={videoRef}
        style={styles.media}
        source={{uri:media}}
        useNativeControls={false}
        resizeMode={ResizeMode.COVER}
        onPlaybackStatusUpdate={(status) => {
            setIsPlaying(status.isPlaying);
          }}
        isLooping={true}
        />
       </View>
       <View style={styles.controls}>
            <TouchableOpacity onPress={togglePlayPause} style={styles.controlButton}>
                {isPlaying?
                <FontAwesome5 name="pause" size={30} color="white" />
                :
                <FontAwesome5 name="play" size={30} color="white" />
                }
            </TouchableOpacity>
      </View>
      <View style={styles.sliderContainer}>
          <Slider
            style={{ width: 300, height: 40 }}s
            minimumValue={0}
            maximumValue={1}
            value={sliderValue}
            onValueChange={onSliderValueChange}
            onSlidingStart={onSlidingStart}
            onSlidingComplete={onSlidingComplete}
            minimumTrackTintColor="#784EF8"
            maximumTrackTintColor="white"
            thumbTintColor="#784EF8"
          />

      </View>
      <TapGestureHandler
            onHandlerStateChange={({ nativeEvent }) => {
              if (nativeEvent.state === State.ACTIVE) {
                setDoubleTapRight(true);
                setTimeout(() => {
                  setDoubleTapRight(false);
                }, 300); // Adjust timeout as needed
              }
            }}
            numberOfTaps={2}
            maxDelayMs={300}
          >
            <View style={styles.rightDoubleTapArea}></View>
          </TapGestureHandler>
          <TapGestureHandler
            onHandlerStateChange={({ nativeEvent }) => {
              if (nativeEvent.state === State.ACTIVE) {
                setDoubleTapLeft(true);
                setTimeout(() => {
                  setDoubleTapLeft(false);
                }, 300); // Adjust timeout as needed
              }
            }}
            numberOfTaps={2}
            maxDelayMs={300}
          >
            <View style={styles.leftDoubleTapArea}></View>
          </TapGestureHandler>
      
        <View >
        
        <FlatList
        data={Comments}
        keyExtractor={(comment) => comment.comment_id.toString()}
            renderItem={renderItem}
        />
        </View>
    </View>
       }
    </View>

  )
}

How can I schedule a task every second but wait with setTimeout() before continuing to the next task?

I am using node.js and I have a task that runs every second like so:

let queue = ["Sample Data 1", "Sample Data 2"]
const job = schedule.scheduleJob('*/1 * * * * *', function () {
    console.log("Checking the queue...")
    if (queue.length > 0) {
        wss.broadcast(JSON.stringify({
            data: queue[0]
        }));
        setTimeout(() => {
            queue.shift();
        }, queue[0].duration);
    }
});

I am wondering how I can make it so that the timeout must finish before the next queue check. Could I use a de-bounce, or is there a better way?

Why useEffect is re-rendering without a state change inside it?

I want to create a continuous loop based component which runs at specific intervals, which will later be used to observe differences in state and save it to Db. But first I want to get the continuous part right. So I used a basic useEffect and put a setInterval, inside it and it worked. But sadly now I dont understand the reason. why the component is printing after every 2 seconds even though there is no state change or a re-render happening, I’m also calling my component only once from the parent. Can any body explain why??

here is my code. Please ignore the buttons you can check the useffect with setInterval part

import { useState, useRef, useEffect, useCallback } from "react";

export default function App() {
  const [state1, setState1] = useState(1);
  
  const saveloop = useCallback(()=>{
    let timeStamp = setInterval(()=>{
      console.log("spinning")
    },2000);
  })

  // this part is printing again and again without any state change
  useEffect(()=>{
    let timeStamp = setInterval(()=>{
      console.log("spinning")
    },[2000]);

    return ()=>{clearInterval(timeStamp)};
  })
  // this part is printing again and again without any state change

  // Initialize a ref to hold the state without causing re-renders
  const stateRef = useRef(1);

  const ConsoleValue2 = () => {
    setState1(prev => prev + 1);
  };

  const smallButton = () => {
    // Update the state without causing a re-render
    stateRef.current += 1;
    // Log the updated state
    console.log(stateRef.current);
  };
  
  console.log("Component rendered again");

  return (
    <div className="App">
      <button onClick={smallButton}>Submit</button>
      <button onClick={ConsoleValue2}>Submit2</button>
    </div>
  );
}

here is the picture of the output
enter image description here

Actually was just checking a clock application code in which you had to update the clock every 1 second, just removed the state in it and this came out. I have no clue why this is happeinning