User is connecting to socket.io server twice

io.on("connection", (socket) => {
    console.log(`User Connected: ${socket.id}`);

    //joining Room
    socket.join(selectedOption);
    socket.broadcast.emit("userConn", `${username} joined ${selectedOption}`);

    socket.on('emitMessage', (data) => {
      if(data.room == selectedOption){
      socket.broadcast.to(selectedOption).emit('message', {username: data.username , message: data.message});
      }
    });

For some reason after the first user has connected, when I login from the second user, they seem to connect twice hence console.log(User Connected: ${socket.id}); runs twice making the server side console looking like

User Connected: pPNqnsAIJAUgDrpkAAAB
User Connected: yZPm7IuY673r1hkUAAAD
User Connected: yZPm7IuY673r1hkUAAAD

This is also resulting in the first user receiving the second user’s messages twice because they seem to be connected twice

I was making a simple socket.io chat server, but the second user’s messages were being received twice by the first user, upon further observation, i noticed that the second user connects to the server twice

Button Disabled after using Time Function inside settimeout

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Daily Checkin</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
  <div class="container">
      <ul>
      <li>
          1. 3Hub<button id="done11" class="btn">
            <a id="claim11" class="link" href="https://3hub.io" target="_blank">Claim</a>
            </button>
      </li>
      </ul>
      </div>

  <footer>&copy;Developed By Srijan</footer>
  </body>
  <script src="script.js"></script>
  </html>

Javascript Code :

var links11 = document.getElementById("claim11");
var done11 = document.getElementById("done11");

links11.addEventListener("click", function(){
    done11.style.backgroundColor = "lightgreen";
    done11.innerText = "Claimed" ;

localStorage.setItem("color",done11.style.backgroundColor);
localStorage.setItem("name",done11.innerText);

})

var storedcolor = localStorage.getItem("color");
var storedvalue = localStorage.getItem("name");
if(storedcolor){
    done11.style.backgroundColor = storedcolor;
    done11.innerText = storedvalue;
}
function nday(){
    var now = new Date();
    now.setUTCHours(4,30,0)
    // console.log(now)
    return now
}

var see = nday();
console.log(see);

    setTimeout(function() {
    localStorage.removeItem("color");
    localStorage.removeItem("name");
    done11.style.backgroundColor = "white";
    done11.innerText = "Claim";
},nday());

now problem is In The Above Code When I am Using nday() inside settimeout my button gets unclcickable and greyed out but instead of it if i am using numbers as time its working.

i dont know why this is happening Already tried using nday or nday() both still same outputjavas

when clicked, JS is taking mw to wrong url in backend (django)

when i click on link it is taking me to ‘/product/api/product/2’ URL but I have defined /api/product/str:pk/

for backend I’m using django.

import React from 'react'
import { Card } from 'react-bootstrap'
import Rating from './Rating'
import { Link } from 'react-router-dom'     // we are using this to load in the same page without reloading whole page

function Product({ product }) {
    return (
        <Card className="my-3 p-3 rounded">
            <Link to={`/product/${product._id}`}>       {/* here we are using link in place of a & to in place of href */}
                <Card.Img src={product.image} />
            </Link>

            <Card.Body>
                <Link to={`/product/${product._id}`}>
                    <Card.Title as="div">
                        <strong>{product.name}</strong>
                    </Card.Title>
                </Link>

                <Card.Text as="div">
                    <div className="my-3">
                        <Rating value={product.rating} text={`${product.numReviews} reviews`} color={'#f8e825'} />
                    </div>
                </Card.Text>

                <Card.Text as="h3">
                    ${product.price}
                </Card.Text>
            </Card.Body>
        </Card>
    )
}

export default Product;

when I place my cursor on product link it is showing the correct URL, but when i click on that link it is taking to wrong pattern on backend server.

How to update Images from list of image urls when Next button is clicked

I want to make a simple html page with 4 images displayed at a time and a next button.

Basically I have list of image urls. At the start, the first 4 images from the lists will be shown in the page. Then, when next button is clicked, the next 4 will be chosen and replace the first 4 images displayed. When it reach the end of the list, it will then go back to the first image on the list. Thank you.

Im not that good in html.

async/await is not yet supported in Client Components when using await supabase

I’m having an issue with fetching data from supabase using await supabase in the client component.

Issue:

  • very slow loading speed between pages, such as http://localhost:3000/dashboard/call-logs
  • Occasionally it shows async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server. error.

https://react.dev/errors/482?invariant=482

This is an extension to this thread: Error: async/await is not yet supported in Client Components in next.js

app/(routes)/dashboard/call-logs/page.tsx

"use client";

import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";
import SingleCallLog from "@/app/_components/call-logs/SingleCallLog";

export const dynamic = "force-dynamic";

// This is a private page: It's protected by the layout.js component which ensures the user is authenticated.
// It's a server compoment which means you can fetch data (like the user profile) before the page is rendered.
// See https://shipfa.st/docs/tutorials/private-page
export default async function Dashboard() {
  const supabase = createClientComponentClient();

  // @ts-ignore
  const {
    data: { user },
  } = await supabase.auth.getUser();
  const userID = user?.id;

  // as you can see I'm using await supabase here to fetch data
  const { data } = await supabase
    .from("firm")
    .select("phoneNumberID")
    .eq("user_id", userID)
    .single();

  const phoneNumberID = data ? data.phoneNumberID : null;
  const { data: callData, error } = await supabase
    .from("calls")
    .select("*")
    .eq("phoneNumberID", phoneNumberID);
  callData.sort(
    (a, b) =>
      new Date(b.inserted_at).getTime() - new Date(a.inserted_at).getTime()
  );

app/(routes)/dashboard/layout.tsx

import { ReactNode } from "react";
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import config from "@/config";
import LeftSidebar from "../../container/LeftSidebar";
import Header from "../../container/Header";
import MobileNavigation from "@/app/container/MobileNavigation";

// This is a server-side component to ensure the user is logged in.
// If not, it will redirect to the login page.
// It's applied to all subpages of /dashboard in /app/dashboard/*** pages
// You can also add custom static UI elements like a Navbar, Sidebar, Footer, etc..
// See https://shipfa.st/docs/tutorials/private-page
export default async function LayoutPrivate({
  children,
}: {
  children: ReactNode;
}) {
  const supabase = createServerComponentClient({ cookies });

  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    redirect(config.auth.loginUrl);
  }

  return (
    <>
      <Header />
      <LeftSidebar />
      <div className="block sm:hidden">
        <MobileNavigation />
      </div>
      {children}
    </>
  );
}

How to link the internal Component with the footer text?

I have to link the Privacy Component with my footer’s “Privacy and Policy” text i tried to connect it with anchor tag but its not working and on the path it is showig 404 Page is not found how can i connect that ?

import Image from "next/image";
import Privact from "./PrivacyComponent"
import PrivacyComponent from "./PrivacyComponent";
export default function Footer() {
  return (
    <>
      {/* Footer Section: With Links Info Newsletter */}
     
              <nav className="flex flex-col space-y-3">
                <a
                  href="#/PrivacyComponent"
                  className="font-medium text-gray-600 hover:text-gray-500"
                >
                  Privacy and Policy
                </a>
                <a
                  href="#services"
                  className="font-medium text-gray-600 hover:text-gray-500"
                >
                  Features
                </a>
                <a
                  href="#products"
                  className="font-medium text-gray-600 hover:text-gray-500"
                >
                  Products
                </a>
                <a
                  href="#testimonials"
                  className="font-medium text-gray-600 hover:text-gray-500"
                >
                  Reviews
                </a>
                <a
                  href="#email"
                  className="font-medium text-gray-600 hover:text-gray-500"
                >
                  Contact
                </a>
              </nav>

I just want to connect the external Privacy component with my footer’s privacy text when i click on it, it will jump to https://localhost:3000.com/PrivacyComponent.

Swiper pagination bullet: styling for visited slides’ pagination bullet as well

I have created this swiper slider with pagination bullets that have a progress bar pagination. It changes color for the bullet (to #000) on active slides. Is there a way for the bullets for the slide that was visited has their colored changed (to #000) as well – so only the unvisited slide’s bullet with the grey #DDD background?

Here’s my code:

HTML:

<!-- Slider main container -->
<div class="swiper-container">
    <!-- Additional required wrapper -->
    <div class="swiper-wrapper">
        <!-- Slides -->
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
        ...
    </div>
    <!-- If we need pagination -->
    <div class="swiper-pagination"></div>
</div>

CSS:

:root {
    --swiper-pagination-bullet-border-radius: 0;
    --swiper-pagination-bullet-width: 40px;
    --swiper-pagination-bullet-height: 2px;
}


body {
  font-family: Helvetica;
  color: #000;
}

.swiper-container {
  width: 100%; height: 100vh;
}

.swiper-wrapper {
  width: 100%; height: 100%; 
}

.swiper-slide {
  font-size: 100px; text-align: center; 
  line-height:100vh;
}

.swiper-pagination-bullet {
    position: relative;
    height: auto;
    opacity: 1;
    margin-right: 20px;
    background-color: transparent;
  
    .progress-bar-bg {
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 1;
        width: 100%;
        height: 2px;
        background-color: #DDD;
    }
    .progress-bar-cover {
        position: absolute;
        bottom: 0;
        left:  0;
        z-index: 2;
        width: 0%;
        height: 2px;
        background-color: #000;
    }
}

.swiper-pagination-bullet-active {
    background-color: transparent;
    b {  
        animation-name: countingBar;
        animation-duration: 3s;
        animation-timing-function: ease-in;
        animation-iteration-count: 1;
        animation-direction: alternate ;
        animation-fill-mode:forwards;
    }
}

@keyframes countingBar {
    0% {width: 0;}
    100% {width:100%;}
}


JS:

var mySwiper = new Swiper('.swiper-container', {
        loop: true,
        slidesPerView: 1,        
        autoplay: {
            delay: 5000,
        }, 
        effect: 'fade',
        fadeEffect: {
          
            crossFade: true
        },
        pagination: {
            el: '.swiper-pagination',
            clickable: 'true',
            type: 'bullets',
            renderBullet: function (index, className) {
                return '<span class="' + className + '">' + '<i class="progress-bar-bg"></i>' + '<b class="progress-bar-cover"></b>'  + '</span>';
              },
        },
})

Any pointers would be an immense help. Thank you so much.

In JavaScript, I tried to add an event listener to visited slide through click and added a ‘visited-slide’ class before. However, it requires a click but won’t automatically updating the bullet’s color as the slide animation goes on.

DateTimePicker not working, textField not updating with selected hours and minutes

I am developing a custom DatePicker using the moment.js library in React. However, I have noticed that the value of my TextField is not updated when I select a new hour and minute in the DatePicker.

import clsx from "clsx";
import moment from "moment";
import React, { useCallback, useMemo } from "react";
import { WiTime3 } from "react-icons/wi";
import { Popover, PopoverContent, PopoverTrigger, Timer } from "../../atoms";
import { TextField } from "../../forms";
import { timeFormat } from "../../util/time-helpers";

export interface TimePickerFieldProps {
  id: string;
  name: string;
  label?: string;
  className?: string;
  value?: moment.Moment;
  onChange: (time: moment.Moment) => void;
  onBlur?: () => void;
  error?: string;
  disabled?: boolean;
  align?: "start" | "center" | "end";
}

export const TimePickerField = React.forwardRef<
  HTMLInputElement,
  TimePickerFieldProps
>(
  (
    {
      id,
      name,
      onChange,
      align,
      className,
      disabled,
      error,
      label,
      onBlur,
      value,
    },
    ref
  ) => {
    const formattedValue = useMemo(
      () => (value ? timeFormat(value) : ""),
      [value]
    );

    const handleSelectTime = useCallback(
      (time?: moment.Moment) => {
        if (time) {
          onChange(time);
        }
      },
      [onChange]
    );

    const handleOpenChange = useCallback(
      (open: boolean) => {
        if (!open) {
          onBlur?.();
        }
      },
      [onBlur]
    );

    return (
      <Popover onOpenChange={handleOpenChange}>
        <PopoverTrigger className="block w-full">
          <TextField
            id={id}
            name={name}
            label={label}
            autoComplete="off"
            error={error}
            disabled={disabled}
            ref={ref}
            readOnly
            suffix={<WiTime3 className="text-primary" />}
            className={clsx("pointer-events-none", className)}
            value={formattedValue}
          />
        </PopoverTrigger>
        <PopoverContent align={align}>
          <Timer selected={value} onSelect={handleSelectTime} />
        </PopoverContent>
      </Popover>
    );
  }
);

import moment from "moment";
import { useState } from "react";
import { HourBar } from "./HourBar/HourBar";
import { MinuteBar } from "./MinuteBar/MinuteBar";

export interface TimerProps {
  selected?: moment.Moment | undefined;
  onSelect?: (time: moment.Moment) => void;
}

export const Timer: React.FC<TimerProps> = ({ onSelect, selected }) => {
  const [selectedTime, setSelectedTime] = useState<moment.Moment>(moment());

  const handleTimeChange = (field: "hour" | "minute", value: number) => {
    setSelectedTime((prevTime) => prevTime.clone().set(field, value));
  };

  return (
    <div>
      <div className="flex flex-row h-[7.75rem] w-[6.5rem] bg-other-transparent-darkest rounded p-2 gap-2">
        <HourBar
          selectedHour={selectedTime.hour()}
          onHourChange={handleTimeChange}
        />
        <MinuteBar
          selectedMinute={selectedTime.minute()}
          onMinuteChange={handleTimeChange}
        />
      </div>
    </div>
  );
};

import { Caption } from "../../../typography";

export interface HourBarProps {
  selectedHour: number;
  onHourChange: (field: "hour" | "minute", value: number) => void;
}

export const HourBar: React.FC<HourBarProps> = ({
  selectedHour,
  onHourChange,
}) => {
  const hours = Array.from({ length: 24 }, (_, i) => i);

  return (
    <div className="flex flex-col overflow-y-auto scrollbar-hide w-full items-center gap-1">
      {hours.map((hour, index) => (
        <Caption
          key={index}
          className={`flex justify-center rounded py-[0.125rem] size-full text-sm cursor-pointer 
        ${hour === selectedHour && "bg-primary text-font-primary"}`}
          onClick={() => onHourChange("hour", hour)}
        >
          {hour}
        </Caption>
      ))}
    </div>
  );
};

import { Caption } from "../../../typography";

export interface HourBarProps {
  selectedMinute: number;
  onMinuteChange: (field: "hour" | "minute", value: number) => void;
}

export const MinuteBar: React.FC<HourBarProps> = ({
  selectedMinute,
  onMinuteChange,
}) => {
  const minutes = Array.from({ length: 60 }, (_, i) => i);
  const filteredMinutes = minutes.filter((minute) => minute % 15 === 0);

  return (
    <div className="flex flex-col overflow-y-auto scrollbar-hide w-full items-center gap-1">
      {filteredMinutes.map((minute, index) => (
        <Caption
          key={index}
          className={`flex justify-center rounded py-[0.125rem] size-full text-sm cursor-pointer 
        ${minute === selectedMinute && "bg-primary text-font-primary"}`}
          onClick={() => onMinuteChange("minute", minute)}
        >
          {minute}
        </Caption>
      ))}
    </div>
  );
};

**Consultation:
**
What could be causing the TextField value to not update correctly when selecting a new hour and minute in the DatePicker? Are there any additional steps I need to take to ensure the value is updated correctly in the UI?

Any suggestions or help would be greatly appreciated! Thank you very much in advance.
When I select a new hour and minutes the value of the TextField is not updating

I want to add a space inbetween the group and team [closed]

So Leadership Team is how I want the end result

atGroupsDefaultColors: {
    LeadershipTeam: "rgba(255, 3, 3, 1)",
    DeveloperTeam: "rgba(230, 83, 0, 0.5)",
    ManagementTeam: "rgba(0, 255, 145, 0.5)",
    SnrAdmin: "rgba(11, 175, 255, 0.5)",
    Admin: "rgba(11, 175, 255, 0.5)",
    SnrModerator: "rgba(11, 175, 255, 0.5)",
    Moderator: "rgba(11, 175, 255, 0.5)",
    trialMod: "rgba(11, 175, 255, 0.5)",
},
staffTeamPage: {
    LeadershipTeam: [

Tried ChatGPT didn’t come up with anything useful.

Character phases through wall one way, but not the other

I’m programming a simple ‘game’ that is just a block that can jump around. I placed a wall, but now the character phases through when moving to the right, but the collision works when going to the right.
Every other part of this is fine. the willImpactMovingLeft function works just fine and should be a mirror of willImpactMovingRight, but right doesn’t work.
simple working code for this example:

<!DOCTYPE html>
    <html>
        <body>
            <div id="cube" class="cube"></div>
            <div id="ground1" class="ground1"></div>
            <div id="ground2" class="ground2"></div>
    <script>
var runSpeed = 5;var CUBE = document.getElementById("cube");var immovables = ["ground1", "ground2"];let Key = {pressed: {},left: "ArrowLeft",right: "ArrowRight",isDown: function (key){return this.pressed[key];},keydown: function (event){this.pressed[event.key] = true;},keyup: function (event){delete this.pressed[event.key];}}
        window.addEventListener("keyup", function(event) {Key.keyup(event);});
        window.addEventListener("keydown", function(event) {Key.keydown(event);});
        setInterval(()=>{
            if (Key.isDown(Key.left)){
                if(willImpactMovingLeft("cube", immovables)!=false){
                    cube.style.left = willImpactMovingLeft("cube", immovables)+"px";
                }else{
                    cube.style.left = CUBE.offsetLeft - runSpeed +"px";
                }
            }
            if (Key.isDown(Key.right)){
                if(willImpactMovingRight("cube", immovables)!=false){
                    cube.style.left = willImpactMovingRight("cube", immovables)+"px";
                }else{
                    cube.style.left = CUBE.offsetLeft + runSpeed +"px";
                }
            }
        }, 10);
        function willImpactMovingLeft(a, b){
            var docA = document.getElementById(a);
            var docB = document.getElementById(b[0]);
            for(var i=0;i<b.length;i++){
                docB = document.getElementById(b[i]);
                if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check
                    if(docA.offsetLeft+docA.offsetWidth>docB.offsetLeft+runSpeed){
                        if(docA.offsetLeft-runSpeed<docB.offsetLeft+docB.offsetWidth){
                            return docB.offsetLeft+docB.offsetWidth;
                        }
                    }
                }
            }
            return false;
        }
        function willImpactMovingRight(a, b){
            var docA = document.getElementById(a);
            var docB = document.getElementById(b[0]);
            for(var i=0;i<b.length;i++){
                docB = document.getElementById(b[i]);
                if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check
                    if(docA.offsetLeft>docB.offsetWidth+docB.offsetLeft-runSpeed){
                        if(docA.offsetLeft+docA.offsetWidth+runSpeed<=docB.offsetLeft){
                                CUBE.textContent = "WIMR";
                                return docB.offsetLeft-docA.offsetWidth;
                        }
                    }
                }
            }
            return false;
        }
    </script><style>.cube{height:50px;width:50px;background-color:red;position:absolute;top:500px;left:500px;}.ground1{height:10px;width:100%;background-color:black;position:absolute;top:600px;left:0;}.ground2{height:150px;width:10px;background-color:black;position:absolute;top:450px;left:700px;}</style></body></html>```
it looks like a lot, but the only problem is the last if statement. Even when the condition is true, it still skips the return number and returns false. Any idea why?

Edit: simplified the code as much as I could.

P.S. **I CANNOT USE THE CONSOLE, I AM ON A MANAGED COMPUTER**

I’d like to create a custom time zone converter, any pointers?

In my database I have a data set with date (startdatetime) and zone (timezone). Zone is posted into the DB from a different application that uses C# DateObject.

Ex. (UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague OR another example (UTC-10:00) Hawaii

I need to create a component that can convert date (startdatetime) and zone (timezone) to the users choosing, so I created a dropdown that uses time zones from moment-timezone library. UNFORTUNATELY it doesn’t convert (or accurately if it does) the C# DateObject format since it’s not in the same format as moment-timezone.

So I either have to create a dictionary where for example it converts ‘(UTC-08:00) Pacific Time (US & Canada)’ to ‘America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0’ or create my own custom dynamic timezone converter. Which I have tried but I keep getting incorrect time.

I could be missing something in moment-timezone docs (since I am new to the library) but as of now this is my existing code (before I was informed that the timezone will be on C# Date Object format and not on moment-timezone format).

import React, {useState, useEffect} from 'react';
import CloseIcon from '@material-ui/icons/Close';
import { makeStyles } from '@material-ui/core/styles';
import { useSelector, useDispatch } from "react-redux";
import {setRunListData, getRunDataAllGroupedAsync, setIsAllRunListDataShown, setTimeZone} from "../actions/index";
import * as Utils from '../../utils/utils';
import { Select, MenuItem, FormControl } from '@mui/material';
import moment from 'moment-timezone';
import {
    Typography,
    IconButton,
    Button,
    Dialog,
    DialogTitle, 
    DialogActions
  } from '@material-ui/core';

const TimeZone = (props) => {
    const { handleClose, isOpen } = props;
    
    const runlist = useSelector(state => state.runlist);
    const jwt = useSelector(state => state.jwt);
    const is_all_run_list_data_shown = useSelector(state => state.is_all_run_list_data_shown);
    const dispatch = useDispatch();

    const [selectedTimeZone, setSelectedTimeZone] = React.useState(localStorage.getItem('time_zone') || 'PST8PDT');
    const [originalRunlist, setOriginalRunlist] = useState(runlist);
    const zones = Utils.zones;

    useEffect(() => {
        setOriginalRunlist(is_all_run_list_data_shown);
    }, [is_all_run_list_data_shown])


    const useStyles = makeStyles((theme) => ({
        dialogWrapper: {
            padding: theme.spacing(2),
            position: 'absolute',
            top: theme.spacing(2),
        },
        dialogTitle: {
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
        },
        closeIcon: {
            marginLeft: 'auto',
        },
        storagesContainer: {
            display: 'flex',
            justifyContent: 'space-evenly', 
            gap: 5, 
            margin: '20px 0px',
        },
        alertContainer: {
            display: 'flex',
            alignItems: 'center',
            marginLeft: '20px 0px',
            overflow: 'hidden',
          },
        inputContainer: {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-evenly',
            margin: '15px 0px',
            //overflow: 'hidden',
        },
        outlineInput: {
            height: 20,
            width: 50,
            marginLeft: 10,
            marginRight: 10,
        },
        buttonContainer: {
            display: 'flex',
            justifyContent: 'space-evenly',
            overflow: 'hidden',
        },
        defaultButton: {
            margin: theme.spacing(1),
            background: 'linear-gradient(113.96deg, #E9F5F5 100%, #D9E7F4 100%)',
            border: '0.5px solid #CCCCCC',
            boxSizing: 'border-box',
            borderRadius: '4px',
            color: '#189AB4',
            width: 150,
            '&:disabled': {
                background: '#f0f0f0', // Change this to the desired disabled background color
                color: '#666666', // Change this to the desired disabled text color
            },
        },
        button: {
            margin: theme.spacing(1),
            background: '-webkit-gradient(linear, left top, right bottom, from(#0075a9), to(#003049))',
            border: '0.5px solid #CCCCCC',
            boxSizing: 'border-box',
            borderRadius: '4px',
            color: 'white',
            width: 150,
            '&:disabled': {
                background: '#f0f0f0', // Change this to the desired disabled background color
                color: '#666666', // Change this to the desired disabled text color
            },
        },
        formControl: {
            "& .MuiInputBase-root": {
              borderWidth: "1px",
              borderStyle: "solid",
              minWidth: "120px",
              width: "280px",
              justifyContent: "center",
              cursor: "pointer" // Set cursor to pointer
            },
            "& .MuiSelect-select.MuiSelect-select": {
              paddingRight: "15px"
            },
            marginLeft: "auto" // Move the FormControl to the right
          },
    }));

    const classes = useStyles();

    const handleChange = (event) => {
        setSelectedTimeZone(event.target.value);
    };

    const handleDefaultRunlistDate = () => {
        setSelectedTimeZone('PST8PDT');
        dispatch(setTimeZone('PST8PDT'));
        originalRunlist ? dispatch(getRunDataAllGroupedAsync(undefined, jwt)) : dispatch(getRunDataAllGroupedAsync(100, jwt));
    }

    function toTimeZone(time, zone) {
        try {
            var format = 'MM/DD/YYYY HH:mm:ss';
            return moment(time, format).tz(zone).format(format);
        } catch (error) {
            console.log(error)
        }
    }

    const handleUpdateRunlistDate = () => {
        let copyRunList = structuredClone(runlist);
        const updatedRunlist = copyRunList.map(entry => {
            if(entry.timezone){
                const startDatetime = toTimeZone(entry.startdatetime, selectedTimeZone);
                entry.startdatetime = startDatetime;
                entry.timezone = selectedTimeZone;
            }
            return entry;
        });
        dispatch(setTimeZone(selectedTimeZone));
        dispatch(setRunListData(updatedRunlist));
    }

    return (
        <>
        <Dialog disableEnforceFocus onClose={handleClose} aria-labelledby="customized-dialog-title" open={isOpen} fullWidth maxWidth={'sm'} classes={{paper: classes.dialogWrapper}}>
            <DialogTitle>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography variant="h6">Time Zone Settings</Typography>
                    <IconButton onClick={handleClose}>
                        <CloseIcon />
                    </IconButton>
                </div>
            </DialogTitle>
            <div className={classes.inputContainer}>
                    <Typography>Time Zone Name:</Typography>
                    <FormControl className={classes.formControl}>
                        <Select
                            labelId="zone-label"
                            id="zone-select"
                            value={selectedTimeZone}
                            onChange={handleChange}
                        >
                            {zones.map((zone, index) => (
                            <MenuItem key={index} value={zone.split('|')[0]}>
                                {zone.split('|')[0]}
                            </MenuItem>
                            ))}
                        </Select>
                    </FormControl>
            </div>
            <div className={classes.buttonContainer}>
                <DialogActions>
                <Button autoFocus color="primary" className={classes.defaultButton} onClick={handleDefaultRunlistDate}>
                    Default
                </Button>
                <Button autoFocus color="primary" className={classes.button} onClick={handleUpdateRunlistDate}>
                    Apply
                </Button>
                </DialogActions>
            </div>
        </Dialog>
        </>
    );

}

export default TimeZone;

Any tips?

Chaining of dispatch HTTP requests isn’t working in Razorpay React

Before I start, I am very new to redux and quite new to React in general. I am integrating the Subscription functionality of Razorpay for an app. Everything is working fine but when I try to chain dispatch of HTTP endpoints, it is not working. Here is the code snippet:


const SubscriptionForm: FC<ISubscriptionForm> = ({ planId, totalCount }) => {

  const { data: user, isFetching } = useAppSelector((store) => store.user.details);

  const dispatch = useAppDispatch();
  const [Razorpay] = useRazorpay();

  const handlePayment = async (subscription_id: any, userDetails: { name: string; email: string; phone: string}) => {


    const options: any = {
      key: process.env.REACT_APP_RAZORPAY_ID,
      amount: "500",
      currency: "USD",
      name: "Test App",
      description: "Test Transaction",
      image: Logo,
      subscription_id: subscription_id,
      handler: (razaorpayResponse: {
        razorpay_payment_id: any;
        razorpay_subscription_id: any;
        razorpay_signature: any;
      }) => {
        dispatch(SubscriptionRestService.verifySignature({ razaorpayResponse}))
          .then((response) => {
            if (SubscriptionRestService.verifySignature.fulfilled.match(response)) {
              console.log("Success:", response);
              dispatch(SubscriptionRestService.updateSubscriptionStatus({ subscriptionId: subscription_id, status: "active" }))
                .then((response) => {
                  if (SubscriptionRestService.updateSubscriptionStatus.fulfilled.match(response)) {
                    console.log("Success:", response);
                    toast.success("Subscription was activated successfully");
                  } else {
                    console.error("Error:", response);
                    toast.error("Subscription activation may have failed. Please contact support if payment was deducted");
                  }
                })
                .catch((error) => {
                  console.error("Error:", error);
                });
              toast.success("Subscription was activated successfully");
            } else {
              console.error("Error:", response);
              toast.error("Subscription may have failed. Please contact support if payment was deducted");
            }
          })
          .catch((error) => {
            console.error("Error:", error);
          });
      },
      theme: {
        color: "#e9e6e6",
      },
      prefill: {
        name: userDetails.name,
        email: userDetails.email,
        contact: userDetails.phone,
      }
    };
    const rzp1 = new Razorpay(options);

    rzp1.open();
  }

This thing works perfectly fine as long as I remove the inner dispatch: dispatch(SubscriptionRestService.updateSubscriptionStatus({ subscriptionId: subscription_id, status: "active" })) But when I add the inner dispatch it gives Invalid Hook Call Error

I want to get away with this error and have the chained dispatch working. The 2 dispatch asyncThunks are as follows:


const verifySignature = createAsyncThunk(
  'subscription/verify_signature',
  async (args:{razaorpayResponse: {
    razorpay_payment_id: any;
    razorpay_subscription_id: any;
    razorpay_signature: any;
  }}, { rejectWithValue }) => {
    try {
      return (await HttpClient.post('/payment/verify-signature', args.razaorpayResponse)).data;
    } catch (error: any) {
      return rejectWithValue(error.message);
    }
});

const updateSubscriptionStatus = createAsyncThunk(
  'subscription/update_status',
  async (args: { subscriptionId: any, status: any }, { rejectWithValue }) => {
    try {
      return (await HttpClient.post('/payment/update-subscription-status', args)).data;
    } catch (error: any) {
      return rejectWithValue(error.message);
    }
});

The verifySignature is working fine but when I dispatch the updateSubscriptionStatus it fails.

Creating Chrome extension, but display text from Javascript file is not showing up on HTML’s display. The HTML is the InnerHTML of another HTML file [duplicate]

Creating a Google Login-In Extension for a personal project so I’ve set up funtionality that allows me to log in to the extension with my Google account and it works. I’m using an initial HTML file called “popup.html” to hold the logic of Google’s Authentication by calling “popup.js” as the backend script, displaying a “Waiting for Log-in” message, and then setting that attribute to display the contents of another HTML file called “authorized.html” after succesful sign-in by setting its contents as the innerHTML property of “popup.html”. The issue is that “authorization.html” own script “authorized.js” will not print anything to either my console nor will it even throw an error on the console despite the other contents of “authorized.html” succefully being displayed. Only the relevant parts of my code are below but I’d like to know why I’m having this issue and how to circumvent it. Thank you

popup.html:

<!DOCTYPE html>
<html>
<head>
  <title>Google OAuth Sign-In</title>
  <script src="popup.js"></script>
</head>
<body>
   <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div >
  </body>
</html>

popup.html:

console.log('popup.js loaded');
document.addEventListener('DOMContentLoaded', function () {
    const NewGUI = document.getElementById('Sign-In TempUI');
  
    chrome.identity.getAuthToken({ interactive: true }, function (token) {
      if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError.message);
        return;
      }
      console.log('Token acquired:', token);
      loadAuthorizedUI(token);
    });


    function loadAuthorizedUI(token) {
        console.log('Debug:', token);
      fetch('authorized.html')
        .then(response => response.text())
        .then(html => {
          console.log('HTML content:', html);
          NewGUI.innerHTML = html;

        })
        .catch(error =>  console.error('Error fetching or processing HTML:', error));

    }
    
  });

authorized.html:

<!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> 
<!DOCTYPE html>
<html>
<head>
  <title>Authorized UI</title>
</head>
<body>
  <h1>Welcome! You are now authorized.</h1>
  <ul id="emailList">
   
  </ul>
  <script src="authorized.js"></script>
  <div>Hit end</div>
</body>
</html>

authorized.js:

//throw new Error('This is a test error from authorized.js');
console.log('authorized.js loaded');

Before, I was starting another document.addEventListener(‘DOMContentLoaded’, function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move the authorized.js script to popup.html, it’ll suddenly display albiet errors. My biggest confusion is that “Welcome! You are now authorized.” and “Hit end” will display on my GUI but the script wont even print, as if its skipping it

Custom tooltip is not working (Google Charts)

I am currently working on google charts and trying to implement custom tooltip. It is still showing the basic default tooltip.

Documentation – https://developers.google.com/chart/interactive/docs/customizing_tooltip_content

Link to the JSFiddle – https://jsfiddle.net/ritesh2627/wo6kb14e/1/

Here is the code: `

      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawVisualization);
function createCustomHTMLContent() {
  return '<div>' +
        'Jan 2023: <strong>1234 kWh</strong>'+
      '</div>';
}
      function drawVisualization() {
        // Some raw data (not necessarily accurate)
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'sdfgadfg');
         data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
  
  data.addColumn('number', '2023');
  data.addColumn('number', '2024');
         data.addRows([
          ['Jan', createCustomHTMLContent(), 165,           614.6],
          ['Feb' ,createCustomHTMLContent(),  135,           682],
          ['Mar' ,createCustomHTMLContent(),  157,           623],
          ['Apr' ,createCustomHTMLContent(),  139,           609.4],
          ['May' ,createCustomHTMLContent(),  136,          569.6],
          ['Jun' ,createCustomHTMLContent(),  165,           614.6],
          ['Aug' ,createCustomHTMLContent(),  135,           682],
          ['Sep' ,createCustomHTMLContent(),  157,           623],
          ['Oct' ,createCustomHTMLContent(),  139,           609.4],
          ['Nov' ,createCustomHTMLContent(),  136,          569.6],
          ['Dec' ,createCustomHTMLContent(),  136,          569.6],
        ]);
        
        var options = {
          vAxis: {title: 'Usage in kWh',titleTextStyle : {
                            fontName : "Oswald",
                            italic : false,
                        },},
          hAxis: {title: 'Month', titleTextStyle : {
                            fontName : "Oswald",
                            italic : false,
                        }},
          seriesType: 'bars',
          series: {0: { color: '#1f6099' },
          1: {type: 'line',pointsVisible: true, color: '#2AB673'}},
          legend: { position: 'bottom', alignment: 'center' },
          tooltip: { isHtml: true },
        };

        var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
       <div id="chart_div" style="width: 900px; height: 500px;"></div>
   

`

Storing settings in cookies

I have made a few settings but each time you refresh your page or go to another page on the website, those settings go back to default. How do i store the users settings in cookies so that they stay as they are when the user refreshes or enters another page? The settings are an option to switch to dark mode and an option to switch languages.

languages:

//html code//
<div class="language">
          <div class="langWrap">
            <a href="#"  language='dutch' class="lang active">NL</a>
            <a href="#"  language='english' class="lang">EN</a>
            <a href="#"  language='spanish' class="lang">ES</a>
            <a href="#"  language='indonesian' class="lang">ID</a>
          </div>
        </div>

//javascript code//
const langEl = [...document.querySelectorAll(".lang")];

let chosenLanguage = 'NL';

langEl.forEach((el) => {
    el.addEventListener("click", () => {
      langEl.map(item => item.classList.contains("active") ? item.classList.remove("active") : false);
      el.classList.add("active");
      chosenLanguage = el.innerText;
      search();
  
      const attr = el.getAttribute("language");
   });
});

dark mode theme:

//html code//
<img src="../images/moon.png" id="icon">

//javascript code//
var icon = document.getElementById("icon");

icon.onclick = function() {
  document.body.classList.toggle("dark-theme");
  if(document.body.classList.contains("dark-theme")){
    icon.src = "images/sun.png";
  } else {
    icon.src = "images/moon.png";
  }
}