How to apply one function to all elements with the same class

I want to click on any of the 3 buttons, and they all will change their background colors at the same time. What is missing or needed to change in my code, for the addEventListener to be able to apply in all elements with the same class?

const one = document.querySelectorAll('.one');

one.forEach((element) => {    
    element.addEventListener("click", () => {
      if (element.style.backgroundColor = "#DCDCDC") {
        element.style.backgroundColor = "#56F1FF";
      } else {
        element.style.backgroundColor = "#DCDCDC";
      }
     })
 });
.one {
  background-color: #DCDCDC;
}

.one:hover {
  background-color: #56F1FF;
}
<button class="one">Catch</button>
<button class="one">Change</button>
<button class="one">Choose</button>

How can you check if a javascript map has a duplicate key

I’m working with a Map in JavaScript and need to check that it doesn’t contain duplicate keys. The map I’m working with is below.

const colors = new Map([
    [1, 'blue'],
    [2, 'orange'],
    [1, 'pink'], // This duplicate key should trigger an error
    [3, 'yellow'],
]);

In this situation because the number 1 is used two times as a key that should throw an error.

I cannot modify the colors variable directly. Instead, I need to make a function that checks for duplicate keys in the Map and throw an error if a duplicate is found.

This is what I currently have. The problem is that when you use a duplicate key in the map it overrides the previous key and value so it’s as if a duplicate key is never in the map.

const colors = new Map([
    [1, 'blue'],
    [2, 'orange'],
    [1, 'pink'], // This duplicate key should trigger an error
    [3, 'yellow'],
]);

const iterator = colors.keys();

console.log(iterator.next().value);
// output: 1

console.log(iterator.next().value);
// output: 2

console.log(iterator.next().value);
// output: 3

MouseEvent behaves strangely when developer tool window is closed

I am developing a flask application with html and javascript for web interface. The application behaves strangely in Mouse events when developer tool is open the mouse press event happens at the position clicked but when closed the response is at a point different than the one clicked. I have removed console.log statements,still the behaviour persist. How can i fix this error?
-swetha

next js middleware infinite redirects

I want to protect my home page if the user is not authenticated he shouldn’t have access to it , a user is authenticated if a cookie exists , if the user is logged in and attempts to change url to login page he should get redirected to home page using next js middleware the problem is if I go back and forth between pages in this case the login page and then sign in i get redirected to login page as expected , the page before the home page is now the login page if i attempt to go back i get a too many redirects message on the screen for a few seconds before i am redirected to home page as expected i have attached a screen shot of my requests from the network tab when this issue occurs network tab i have been stuck with this issue for a few days and it’s really frustrating . `

import { NextRequest, NextResponse } from 'next/server';

export async function middleware(request: NextRequest, response:
NextResponse) {

const isUserLogged = request.cookies.get('chat_accessToken');

const pathname = request.nextUrl.pathname;
const authPaths = ['/login', '/register'];

if (
 (isUserLogged && pathname == '/') ||
 (isUserLogged && authPaths.includes(pathname) && pathname !== '/home/chats')
) {
 return NextResponse.redirect(new URL('/home/chats', request.url));
}
if (!pathname.includes('/login') && !isUserLogged) {

   return NextResponse.redirect(new URL('/login', request.url));
 } 
   return NextResponse.next();

 }
export const config = {
   matcher: [
  /*
   * Match all request paths except for the ones starting with:
   * - api (API routes)
   * - _next/static (static files)
   * - _next/image (image optimization files)
   * - favicon.ico (favicon file)
   */
   '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

`

i have changed a condition to ensure that the page doesn’t redirect to itself (didn’t work)

Testing a react component library project using vite

I have a library project using TS, React, and vite for bundler. Folder structure looks like this

- LibraryProject
 - src
  - main
   - TestComponent.tsx
  - hooks
   - hookFile.ts
  - enums
   - enumFile.enum.ts

My current vite config builds a lib properly and I am able to use that in a separate React demo project.

To import my Library project into the react demo project, I am using the default npm install command followed by the ../pathToLibraryProject. Once the project is linked I am able to reference the main file but unable to import enums or hooks.

Current import statement,

import TestComponent, { enumA } from "library-project";

TestComponent as I mentioned is imported correctly but not ENUM_A.

Error,

ERROR in ./src/App.js 46:22-39
export 'enumA' (imported as 'enumA') was not found in 'library-project' (possible exports: default)

Can anyone point out what can possibly fix this?

Thanks.

Not getting the Chat History between 2 Users (Using Strapi and Socket.io with React Native)

Hey community I am using the Strapi and Socket.io to implement one on one chatting means real time chatting with React Native.
My implementation is working fine Sending and receiving message is working fine .But the chat history is not getting fetched it is showing the Null array Although there are messages available in strapi content manager or in Database .

import React, {useState, useEffect} from 'react';
import {
  View,
  TextInput,
  Text,
  StyleSheet,
  TouchableOpacity,
  SafeAreaView,
  ScrollView,
  Keyboard,
  KeyboardAvoidingView,
  Platform,
  TouchableWithoutFeedback,
} from 'react-native';
import {WebSocketService} from '../../../services/WebSocketService';
import {format} from 'date-fns';
import {backendBaseUrl} from '../../../services/WebSocketService';
import {useRoute} from '@react-navigation/native';
import {useSelector} from 'react-redux';
import apiEndPoints from '../../../constants/apiEndPoints';
import {DefaultEventsMap} from '@socket.io/component-emitter';
import {Socket} from 'socket.io-client';
import {Image} from 'react-native';
import images from '../../../assets/images';
import useStyles from './style';
import icons from '../../../assets/icons';

interface Message {
  id: number;
  attributes: {
    content: string;
    sender: {
      data: {
        id: number;
      };
    };
    recipient: {
      data: {
        id: number;
      };
    };
    timestamp: string;
  };
}

interface RouteParams {
  data: number;
  name: string;
  friendData: any;
}

const Chatopen: React.FC = ({navigation}) => {
  const {styles, colors, sizes} = useStyles();

  const userToken = useSelector((state: any) => state.user?.user?.jwt);
  const userId = useSelector((state: any) => state.user?.user?.user?.id);
  const [messages, setMessages] = useState<Message[]>([]);
  const [messageInput, setMessageInput] = useState<string>('');
  const route = useRoute();
  const {data, name, friendData} = route.params as RouteParams;
  let friendId = data;
  // console.log('Friend Id:', data);
  // console.log('UserId', userId);
  // console.log('Name is ', name);
  console.log('Friend Data is  ', JSON.stringify(friendData, null, 2));

  useEffect(() => {
    let socket: Socket<DefaultEventsMap, DefaultEventsMap>;

    const connectWebSocket = async () => {
      if (userToken) {
        socket = WebSocketService(userToken);
        console.log('socket');
        socket.on('connect', () => {
          console.log('Connected to WebSocket');
        });

        socket.on('message:create', (message: {data: Message}) => {
          console.log('Received message:', message);
          setMessages(prevMessages => [...prevMessages, message.data]);
        });
      }
    };
    fetchMessages();
    connectWebSocket();

    return () => {
      if (socket) {
        socket.off('message:create');
        socket.disconnect();
      }
    };
  }, [userToken, friendId]);

  const fetchMessages = async () => {
    try {
      const response = await fetch(
        `${backendBaseUrl}/api/messages?populate=*&filters[$or][0][sender][id][$eq]=${friendId}&filters[$or][0][recipient][id][$eq]=${userId}&filters[$or][1][sender][id][$eq]=${userId}&filters[$or][1][recipient][id][$eq]=${friendId}&pagination[page]=1&pagination[pageSize]=10`,

        {
          headers: {
            Authorization: `Bearer ${userToken}`,
            'Content-Type': 'application/json',
          },
        },
      );
      const responseData = await response?.json();
      console.log('Hello Testing this functions');
      console.log('Response Data', responseData);

      if (responseData?.data) {
        setMessages(responseData?.data);
      } else {
        setMessages([]); // Ensure it's an empty array if there's no data
      }
    } catch (error) {
      console.error('Error fetching messages:', error);
    }
  };
  console.log(
    'Response ================= >> ',
    JSON.stringify(messages, null, 2),
  );

  const sendMessage = async () => {
    if (messageInput.trim() === '') return;

    const newMessage = {
      data: {
        content: messageInput,
        sender: userId,
        recipient: friendId,
        timestamp: formattedDate(),
      },
    };

    try {
      const token = userToken;
      await fetch(`${apiEndPoints.BASE_URL}/api/messages?populate=*`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newMessage),
      });

      setMessageInput('');
    } catch (error) {
      console.error('Error sending messages:', error);
    }
  };

  const formattedDate = () => {
    const currentDate = new Date();
    return format(currentDate, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  };

  return (
    <SafeAreaView style={styles.container}>
      <View>
        <View style={styles.chatHeaderContainer}>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Image source={images.ARROW_LEFT} tintColor={colors.BACKGROUND} />
          </TouchableOpacity>
          <Image
            source={{
              uri: `${apiEndPoints.BASE_URL}${friendData.profileImage.url}`,
            }}
            style={styles.dpImageStyles}
          />
          <Text style={styles.headerText}>{name}</Text>
        </View>
      </View>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={{
          flex: 1,
        }}>
        {messages && messages.length > 0 ? (
          messages.map(item => (
            <View
              key={item.id.toString()}
              style={[
                styles.message,
                item?.attributes?.recipient?.data?.[0]?.id === userId
                  ? styles.receivedMessage
                  : styles.sentMessage,
              ]}>
              <Text style={styles.messageText}>{item.attributes.content}</Text>
              <Text style={styles.timestamp}>{item.attributes.timeStamp}</Text>
            </View>
          ))
        ) : (
          <Text
            style={{
              textAlign: 'center',
              fontSize: 16,
              color: '#333',
              marginTop: 16,
            }}>
            No messages yet
          </Text>
        )}
        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            value={messageInput}
            placeholderTextColor={'black'}
            onChangeText={text => {
              setMessageInput(text);
            }}
            placeholder="Type a message..."
          />
          <TouchableOpacity style={styles.sendButton} onPress={sendMessage}>
            <Image source={icons.SEND} tintColor={'#008000'} />
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

export default Chatopen;

This is my code and i have also tried the GPT’s Solution where it asked me to add pagination but didn’t got the results now any one please help me it approx 7 days fighting with this bug.

Problem with Javascript ParentNode – Div containers

There is a problem with parentnodes divs, and I really don’t know what I’m doing wrong

I have tried different things but I can’t get it to display correctly, and the console always gives me the same error. So I would appreciate the help of someone more experienced than me to try to solve this problem.

The result should be:

<div class="ipcl-embed">
    <div class="ipcl-embed-player">theplayer embed HERE</div>
</div>
        

But what I get is this:

The output:

enter image description here

The console’s error message:

Uncaught DOMException: Node.insertBefore: Child to insert before is not a child of this node
processNode ...
EventListener.handleEvent* 

The Style:

 <style>
            .ipcl-embed {
                position: relative;
                padding-bottom: 56.25%;
                height: auto;
                overflow: hidden;
                background-color: #000000;
                border-radius: 5px;
                cursor:pointer;
            }
            .ipcl-embed-player {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }
          </style>

The script:

<script>
document.addEventListener("DOMContentLoaded", function() {
    function processNode(node) {
        if (node.nodeType === 3) {
            var parent = node.parentNode;
            var text = node.nodeValue;
            var regex = /\[ipcl=(.*?)\]/g;
            var match = regex.exec(text);
             while (match) {
                if (match[1].includes("(.*?)")) {
                    match = regex.exec(text);
                    continue;
                }
                var before = document.createTextNode(text.slice(0, match.index));
                var embedDiv = document.createElement('div');
                embedDiv.className = 'ipcl-embed';
                var embedId = 'ipcl-embed-player';
                embedDiv.id = embedId;
                parent.insertBefore(before, node);
                parent.insertBefore(embedDiv, node);
                var after = document.createTextNode(text.slice(regex.lastIndex));
                parent.insertBefore(after, node);
                parent.removeChild(node);
                var script = document.createElement('script');
                script.innerHTML = `theplayer.embed('` + embedId + `', '` + match[1] + `',{locale: "auto", autoplay: true});`;
                parent.insertBefore(script, after);
            }
        } else if (node.nodeType === 1) {
            for (var i = 0; i < node.childNodes.length; i++) {
                processNode(node.childNodes[i]);
            }
        }
    }
    processNode(document.body);
});
</script>

Error fetching user data: Cannot read properties of undefined (reading ‘request’)

Problem:

I’m trying to fetch user data from Auth0 using their Management API in my Express app, but I’m encountering the following error:

Error fetching user data: Cannot read properties of undefined (reading ‘request’) Failed to update user metadata: Error: Failed to fetch user data from Auth0

This error occurs when making the Axios request to the /users-by-email Auth0 API endpoint. I’m not sure what might be causing the issue since I’ve double-checked the configuration. This request is called on this url: http://localhost:3000/fetch-user/[email protected]

the error is printed out here:

console.error('Error fetching user data:', error.response ? error.response.data : error.message);

and is most likley happening here:

const response = await axios.request(config);

Code:

Here is the relevant part of my Express server:

const express = require('express');
const axios = require('axios');
require('dotenv').config();

const app = express();

// Middleware to parse JSON request body
app.use(express.json());

// Function to get user data from Auth0 using email
async function getUserFromEmail(email) {
  const token = process.env.AUTH0_MANAGEMENT_API_TOKEN;  // Auth0 Management API Token from .env file
  const config = {
    method: 'get',
    url: `https://${process.env.AUTH0_DOMAIN}/api/v2/users-by-email?email=${encodeURIComponent(email)}`,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    }
  };

  try {
    const response = await axios.request(config);
    console.log('Fetched User Data:', response.data);
    return response.data;
  } catch (error) {
    console.error('Error fetching user data:', error.response ? error.response.data : error.message);
    throw new Error('Failed to fetch user data from Auth0');
  }
}

// Route to fetch user data
app.get('/fetch-user/:email', async (req, res) => {
  try {
    const email = req.params.email;
    const userData = await getUserFromEmail(email);
    res.json(userData);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

Error Message:

Error fetching user data: Cannot read properties of undefined (reading ‘request’) Failed to fetch user data from Auth0

What I’ve Tried:

  1. Verified that the Auth0 Management API token (AUTH0_MANAGEMENT_API_TOKEN) and domain (AUTH0_DOMAIN) are correctly set in my .env file.

  2. Checked that the API endpoint URL for Auth0 (/api/v2/users-by-email) is correct and accessible.

  3. Logged the token and configuration to ensure they are being set correctly before making the Axios request.

  4. Tried updating the Axios request syntax, but the error persists.

Environment:

  • Node.js version: 14.x

  • Express version: 4.x

  • Axios version: 0.21.x

Question:

How can I resolve the "Cannot read properties of undefined (reading 'request')" error, and successfully retrieve user data from Auth0? Is this an issue with how I’m making the Axios request, or could it be a configuration problem on the Auth0 side? Any insights or guidance would be greatly appreciated!

How to stop re rendering of Parent Component when navigated to nested route?

enter image description here

I have two urls

/soccer/teams

/soccer/teams/:team_id

In Teams.js I have a api call to get list of teams when mounted.

import React, { useEffect, useState } from 'react'
import { useSoccerStore } from '../../../zustand/store';
import api from '../../api/api';
import Skeleton from 'react-loading-skeleton';
import { NavLink, Outlet } from 'react-router-dom';

const Teams = () => {
    const [teams, setTeams] = useState([]);
    const currentSeason = useSoccerStore((state) => state.currentSeason);

    const fetchTeamsData = async () => {
        try {
            const result = await api.get(`soccer/teams/${currentSeason?.season_id}`);
            const teamdata = result.data?.data;

            if (teamdata) {
                setTeams(teamdata);
            }
        } catch (error) {
            console.error(error);
        }
    };

    useEffect(() => {
        console.log('ParentComponent mounted');
        fetchTeamsData();
    }, []);


    return (
        <>
            <div className="w-100 teams-section">
                <div className="team-nav row">
                    {
                        teams.length <= 0 
                        ? <Skeleton count={1} height={50} className='mb-1'/>
                        : teams.map((item) => (
                            
                            <div
                                className="col-lg-1 col-md-2 col-6"
                                key={item.id}
                            >
                                <NavLink
                                    to={`${item.id}`}
                                >
                                    <div className="team-nav-item" >
                                        <img
                                            src={item.team_logo_lg}
                                            alt={item.team_official_name}
                                        />
                                    </div>
                                </NavLink>
                            </div>
                        ))
                    }
                </div>

                <div className="team-body">
                    <Outlet />
                </div>
            </div>
        </>
    )
}

export default Teams

In Team.js I have individual team data

import React from 'react'
import { useParams } from 'react-router-dom';

const Team = () => {
    const { team_id } = useParams();
    console.log(team_id);
    
    return (
        <h1>Team {team_id}</h1>
    )
}

export default Team

The Problem:

When I go to /soccer/teams/1 url the teams list is also updating. I don’t want parent component to re render and hit that api. So that it only render child component.

{
    path: "/soccer",
    element: <Soccer />,
    children: [
      {
        index: true,
        element: <Navigate to="/soccer/standings" replace />,
      },
      {
        path: 'standings',
        element: <Standings />,
      },
      {
        path: 'teams',
        element: <Teams />,
        children: [
          {
            path: ":team_id",
            element: <Team />,
          }
        ],
      },
    ],
  }  

I tried implementing react-router-dom <Outlet/> so it doesn’t render parent component.

But it didn’t work

Styled Unicode Characters to Plain Text

I have this code that converts plain text to Unicode styled characters:

function convertText(text, style) {

  // 1. Convert the text to the bold type with the unicode.
  const conv = {
    c: function(text, obj) {return text.replace(new RegExp(`[${obj.reduce((s, {r}) => s += r, "")}]`, "g"), e => {
      const t = e.codePointAt(0);
      if ((t >= 48 && t <= 57) || (t >= 65 && t <= 90) || (t >= 97 && t <= 122)) {
        return obj.reduce((s, {r, d}) => {
          if (new RegExp(`[${r}]`).test(e)) s = String.fromCodePoint(e.codePointAt(0) + d);
          return s;
        }, "")
      }
      return e;
    })},
    bold: function(text) {return this.c(text, [{r: "0-9", d: 120734}, {r: "A-Z", d: 120211}, {r: "a-z", d: 120205}])},
    italic: function(text) {return this.c(text, [{r: "A-Z", d: 120263}, {r: "a-z", d: 120257}])},
    boldItalic: function(text) {return this.c(text, [{r: "A-Z", d: 120315}, {r: "a-z", d: 120309}])},
  };

  if(style == 'bold')
    return(conv.bold(text));
  else if(style == 'italic')
    return(conv.italic(text));
  else if(style == 'bolditalic')
    return(conv.boldItalic(text));
  else
    return text;
}

which I have found on this link:
text

I tried reversing the code to convert the styled unicode characters to plain text but failed. Hopefully somebody could reverse the code to get the plain text from the styled unicode characters.

How to use conditional rendering with typscript discriminated union?

I have these types

type Props = {
  routes: Array<RouteInfo>;
  placment: MenuPlacmentTopBottom | MenuPlacmentLeftRight;
  fullHeight?: boolean;
};

and in my component I do a check on which it is:

const Navigation: React.FC<Props> = (props) => {
  const { placment } = props;

  if (placment === MenuPlacmentTopBottom.Top || placment === MenuPlacmentTopBottom.Bottom) {
    return <HeaderTopBottom {...props} />;
  } else {
    return <SideNav {...props} />;
  }
};

The HeaderTopBottom placment prop is of type: MenuPlacmeenter code herentTopBottom

While the SideNav is of type: MenuPlacmentLeftRight

I get the following error:

type ‘{ routes: RouteInfo[]; placment: MenuPlacmentTopBottom |
MenuPlacmentLeftRight; fullHeight?: boolean; }’ is not assignable to
type ‘Props’. Types of property ‘placment’ are incompatible.
Type ‘MenuPlacmentTopBottom | MenuPlacmentLeftRight’ is not assignable to type ‘MenuPlacmentTopBottom’.
Type ‘MenuPlacmentLeftRight.Left’ is not assignable to type ‘MenuPlacmentTopBottom’.

I dont get why? Should my check not be enough? I want to avoid explicit casting.

Using typescript 4.9.5

400 Bad Request when sending JSON from JavaScript to C# in ASP.NET Razor Pages

I’m trying to send JSON data from JavaScript to my C# code in an ASP.NET Razor Pages project, but I keep getting a “400 Bad Request” error. The goal is to parse and handle the data in the C# backend. Below is my JavaScript and C# code:

JavaScript code:

const data = [
    {
        "customer_name": "Abdullah Al Mahmud",
        "mobile": 7654,
        "bookName": "Physics 1st paper",
        "unit_price": 250,
        "quantity": 1,
        "discount": 0,
        "total": 250
    },
    {
        "customer_name": "Abdullah Al Mahmud",
        "mobile": 7654,
        "bookName": "Physics 1st paper",
        "unit_price": 250,
        "quantity": 6,
        "discount": 0,
        "total": 1500
    }
];

$.ajax({
    url: '/Index',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ data }), 
    success: function(result) {
        console.log(result);
    }
});

C# code:

public class IndexModel : PageModel
{
    [BindProperty]
    public List<OrderData> Orders { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        using (var reader = new System.IO.StreamReader(Request.Body))
        {
            var body = await reader.ReadToEndAsync();
            Orders = JsonConvert.DeserializeObject<List<OrderData>>(body);
            foreach (var order in Orders)
            {
                System.Diagnostics.Debug.WriteLine($"Customer: {order.CustomerName}, Book: {order.BookName}, Total: {order.Total}");
            }
        }

        return new JsonResult(new { message = "Data received successfully", orders = Orders });
    }
}

public class OrderData
{
    [JsonProperty("customer_name")]
    public string CustomerName { get; set; }

    [JsonProperty("mobile")]
    public int Mobile { get; set; }

    [JsonProperty("bookName")]
    public string BookName { get; set; }

    [JsonProperty("unit_price")]
    public decimal UnitPrice { get; set; }

    [JsonProperty("quantity")]
    public int Quantity { get; set; }

    [JsonProperty("discount")]
    public decimal Discount { get; set; }

    [JsonProperty("total")]
    public decimal Total { get; set; }
}

In the browser’s network tab, I can see that the request is being sent, but the server responds with a 400 Bad Request.
What I’ve tried:

  1. I’ve made sure the JavaScript is sending the data as JSON.
  2. I tried reading the request body in C# and deserializing it using JsonConvert.DeserializeObject.
  3. I added contentType: ‘application/json’ in the AJAX request.

Potential Issue: I suspect the issue could be related to the way I’m sending the data. In JavaScript, I’m wrapping the array of objects in an object with a data key, but maybe that’s causing issues with how the backend expects the format.

Question:

  • What am I missing here that might be causing the 400 Bad Request?
  • Should I structure the JavaScript request differently or adjust my C# code to handle the incoming data properly?
    Any help would be appreciated!

How to use string laptimes in Chartjs

I have an array of lap times as strings shown below:

['00:01:41.413000', '00:01:38.790000', '00:01:38.917000', '00:01:38.470000', '00:01:37.906000', '00:01:37.997000', '00:01:37.774000', '00:01:37.669000', '00:01:37.890000', '00:01:37.739000', '00:01:37.593000', '00:01:37.778000', '00:01:37.701000', '00:01:37.707000', '00:01:37.826000', '00:01:37.851000', '00:01:37.987000', '00:01:38.068000', '00:01:38.017000', '00:01:38.123000', '00:01:38.172000', '00:01:38.192000', '00:01:38.231000', '00:01:38.399000', '00:01:38.641000', '00:01:38.575000', '00:01:38.927000', '00:01:39.265000', '00:01:47.873000', '00:01:58.989000', '00:01:36.688000', '00:01:36.824000', '00:01:37.022000', '00:01:36.871000', '00:01:37.100000', '00:01:36.968000', '00:01:36.984000', '00:01:37.071000', '00:01:36.957000', '00:01:36.962000', '00:01:37.380000', '00:01:36.865000', '00:01:36.582000', '00:01:36.414000', '00:01:36.618000', '00:01:36.500000', '00:01:36.628000', '00:01:36.739000', '00:01:36.602000', '00:01:37.055000', '00:01:37.132000', '00:01:36.842000', '00:01:36.843000', '00:01:36.748000', '00:01:36.427000', '00:01:36.387000', '00:01:36.402000', '00:01:36.171000', '00:01:35.967000', '00:01:36.343000', '00:01:36.013000', '00:01:36.931000']

I want to use Chart.js and moment.js to use this data as the graph data for a linear chart, without having to convert it to milliseconds etc. I want the format for the data to be “mm:ss.SSS” on the graph. I have no idea how to do this using moment and the time cartesian parsers in Chart.js

The only relevant resources I could find were outdated versions of Chartjs. I have tried converting the strings into moments of milliseconds and setting:

 type: "time",
 time: {
   unit: "millisecond",

   displayFormats: {
     millisecond: "mm:ss.SSS",
    },
 },

on the y-axis. My full chart without the time parser is below:

  new Chart(ctx, {
    type: "line",
    data: {
      // Generates an array from 1 to total laps to label the axis
      labels: Array.from({ length: totalLaps }, (_, i) => i + 1),
      datasets: datasets,
    },
    options: {
      scales: {
        x: {
          title: {
            display: true,
            text: "Lap number",
            padding: {
              top: 24,
            },
          },
        },
        y: {
          title: {
            display: true,
            text: "Lap time",
            padding: {
              bottom: 24,
            },
          },
        },
      },

      // Styles the tooltip hover

      plugins: {
        tooltip: {
          enabled: true,
          backgroundColor: "rgba(0, 0, 0, 0.7)",
          titleColor: "#ffffff",
          borderColor: "rgba(255, 255, 255, 0.5)",
          borderWidth: 1,
          padding: 16,

          titleFont: {
            size: 16,
          },
          bodyFont: {
            size: 16,
          },

          titleAlign: "center",
          titleMarginBottom: 8,
          cornerRadius: 8,
          displayColors: false,

          useHTML: true,

          callbacks: {
            title: (tooltipItems) => `Lap ${tooltipItems[0].label}`,
            label: (tooltipItem) => {
              const dataset = datasets[tooltipItem.datasetIndex];
              const value = tooltipItem.raw;

              const lapCompound = dataset.laps[tooltipItem.dataIndex][1];

              return `${dataset.label}: ${value} [${lapCompound}]`;
            },
          },
        },
      },
    },
  });```

How to make the audio playback work exactly at call received?

I am using nodejs and The google api TelephonyCallback only works with three status updates. I am to use these status updates to initiate audio playback. Unfortunately the one I need – the status update called Offhook – is initiated when the call is ringing or answered or in progress. I need a specific one where it is working only when the caller answers the call, so that the audio will play at the right time.

I got the text and calls working but no audio playback when the call is answered