the bost isnt sending attachment

const { Client, GatewayIntentBits, AttachmentBuilder } = require('discord.js');
const { createCanvas, loadImage } = require('canvas');

const { token } = require('./config.json');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMembers,
    ],
});

client.once('ready', () => {
    console.log('Bot is online!');
});

client.on('guildMemberAdd', async member => {
    const channel = member.guild.channels.cache.find(channel => channel.name === 'welcome');
    if (!channel) return;

    const canvas = createCanvas(700, 250);
    const ctx = canvas.getContext('2d');

    // Clear canvas with transparency
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Set text properties
    ctx.font = '40px sans-serif';
    ctx.fillStyle = '#ffffff';

    // Draw welcome text
    ctx.fillText(`Welcome to the server, ${member.displayName}!`, 50, 100);

    // Load and draw member's avatar
    const avatar = await loadImage(member.user.displayAvatarURL({ format: 'jpg' }));
    ctx.drawImage(avatar, 50, 120, 80, 80); // Adjust position and size as needed

    // Create attachment from canvas buffer
    const attachment = new AttachmentBuilder(await canvas.toBuffer(), 'welcome-image.png');

    // Send welcome message with attachment
    channel.send(`Welcome to the server, ${member}!`, { files: [attachment] });
});

i made discord.js bot using attachmentBuilder but the bot isnt sending image it just send welcome message without image enter image description here thats image

so i tried to much to get help from ai or else but nothing

Print string array in angular template not working

I have an array which I want to print in angular template.
{{arrayValue}} when printed it shows value ["1","2","3","4"].

When I try to print values individually they work just fine but for some reason following two loops aren’t working I have tried other available solutions too.

<div class="number-counter"> <!-- This outputs as desired 1-4 in span -->
  <span>{{arrayValue[0]}}</span>
  <span>{{arrayValue[1]}}</span>
  <span>{{arrayValue[2]}}</span>
  <span>{{arrayValue[3]}}</span>
</div>

I have tried following two solutions as I want to wrap each item span when printed so I could style them in a counter format.

<div class="number-counter" ng-repeat="item in arrayValue">
<span>{{item}}</span>
</div>

Other solution I have tried:

<div class="number-counter" *ngFor="let item of arrayValue">
<span>{{item}}</span>
</div>

dispatch and connect in redux not working

I am a beginner to redux. I am trying to follow this tutorial to learn but it is a little outdated. I am having trouble with getting the code to work. I am building a social app following tutorial using react expo.
In the following code, there are a few issues:

  • fetchUser and fetchUserPosts are never called (the console log statements inside them never print)
import { USER_STATE_CHANGE, USER_POSTS_STATE_CHANGE } from '../constants/index.js'
import firebase from 'firebase/app'
import { auth, db } from '../../firebaseConfig.js'
import { doc, getDoc } from "firebase/firestore";


export function fetchUser() {
    console.log("fetchUser");
    return async (dispatch) => {
        const docRef = doc(db, "users", auth.currentUser.uid);
        const docSnap = await getDoc(docRef)
            // .then((docSnap) => {
            //     if (docSnap.exists) {
            //         console.log("fetch user dispatch");
            //         dispatch({ type: USER_STATE_CHANGE, currentUser: docSnap.data() })
            //     } else {
            //         console.log('does not exist')
            //     }
            // }).catch((error) => {
            //     console.log("Error getting document:", error);
            // });
        if (docSnap.exists) {
            console.log("fetch user dispatch");
            dispatch({ type: USER_STATE_CHANGE, currentUser: docSnap.data() })
        } else {
            console.log('does not exist')
        }
    }
}

export function fetchUserPosts() {
    console.log("fetchUserPosts");
    return ((dispatch) => {
        console.log("fetchUserPosts inside return");
        firebase.firestore()
            .collection("posts")
            .doc(auth.currentUser.uid)
            .collection("userPosts")
            .orderBy("creation", "asc")
            .get()
            .then((snapshot) => {
                let posts = snapshot.docs.map(doc => {
                    const data = doc.data();
                    const id = doc.id;
                    return { id, ...data }
                })
                console.log("posts" + posts)
                dispatch({ type: USER_POSTS_STATE_CHANGE, posts })
            })
    })
}
  • when i uncomment the mapstatetoprops in my profile.js, it throws the error: no store property exists. my console log (console.log({ currentUser, posts });) also gives undefined. as a comment, the code runs and rest of the app runs but again the console log mentioned gives undefined.
import React from 'react'
import { View, Text, Image, FlatList } from 'react-native'
import { auth } from '../../firebaseConfig'

import { fetchUserPosts } from '../../redux/actions/index.js'

import { connect } from 'react-redux'

function Profile(props) {
  const { currentUser, posts } = props;
  console.log({ currentUser, posts });
  return (
    <View>
      <Text>Profile</Text>
    </View>
  )
}

const mapStateToProps = (state) => ({
  // currentUser: store.userState.currentUser,
  // posts: store.userState.posts,
})

export default connect(mapStateToProps, null)(Profile);

Here is my main js relavent code:

const mapStateToProps = (state) => ({ currentUser: state.user, });

const mapDispatchProps = (dispatch) => bindActionCreators({ fetchUser, fetchUserPosts }, dispatch);

export default connect(mapStateToProps, mapDispatchProps)(main);

and here is the user js.

import { USER_STATE_CHANGE, USER_POSTS_STATE_CHANGE } from '../constants/index'

const initialState = {
    currentUser: null,
    posts: []
}

export const user = (state = initialState, action) => {
    switch(action.type){
        case USER_STATE_CHANGE:
            return {
                ...state,
                user: action.currentUser
            }
        case USER_POSTS_STATE_CHANGE:
            return {
                ...state,
                posts: action.posts
            }
        default:
            return state;
    }
}

my constants:

export const USER_STATE_CHANGE = 'USER_STATE_CHANGE'
export const USER_POSTS_STATE_CHANGE = 'USER_POSTS_STATE_CHANGE'

Sorry for the long post. I have spent hours on it and I have no idea where I could make changes. i have tried everything in my knowledge. please let me kwow if anything else is needed.

Positioning error of a container in the viewport that’s generating an undesired horizontal scroll

I’m trying to program a simple React page that’ll automatically scroll to the content inside the div “newContent”. This container must be below the container Content because I only want this container to be visible at the beginning, making the container that’s below invisible until you scroll down to it by clicking the scroll button. My CSS is messing up the positioning of the lower content because instead of scrolling vertically down to it revealing it’s appearance, it scrolls in a diagonal way to the right. I think the property “position: absolute” is messing it up but when I remove that property, it sticks up on the top of the viewport, not hiding it at the bottom. I need it to bee centered at the bottom since it’s a video player, and it has to be responsive, so I tried giving it a top: 100vh, but that didn’t work either. Hopefully someone can help me fix this error. Thanks!

App.js:

`import React, { useState, useEffect, useRef } from 'react';
 import './App.css';
 import logo from './assets/logo.png';
 import whoweare from './assets/whoweare.png';
 import playIcon from './assets/playIcon.png';

 function App() {
   const [loading, setLoading] = useState(true);
   const newContentRef = useRef(null); // Referencia al elemento newContent

  useEffect(() => {
   const contentLoadingTimer = setTimeout(() => {
   setLoading(false);
   }, 2000); // Simula una carga de 2 segundos

   const logoDisappearingTimer = setTimeout(() => {
    setLoading(false);
    }, 3000); // Después de 1 segundo adicional

   return () => {
    clearTimeout(contentLoadingTimer);
    clearTimeout(logoDisappearingTimer);
   };
   }, []);

  const handleButtonClick = () => {
    if (newContentRef.current) {
    newContentRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

 return (
    <div className={`App ${loading ? 'loading' : ''}`}>
    {loading ? (
    <img src={logo} alt="Logo" className="logo" />
    ) : (
        <div className="content-container">
        <div className="content">
           <img className="whoweare" src={whoweare} alt="quienesomos" />
        <button className="playButton" onClick={handleButtonClick}>
           <img src={playIcon} alt="Play" />
        </button>
        </div>
        <div className="newContent" ref={newContentRef}>
            <video controls className="videoPlayer">
            <source src="ruta/al/video.mp4" type="video/mp4" />
            </video>
       </div>
    </div>
    )}
    </div>
    );
    }

export default App;`

App.css:

` .App {
position: relative;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}

.logo {
  width: 200px; /* Ajusta el tamaño según tu diseño */
  height: auto; /* Esto mantendrá la proporción de la imagen */
}
.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
 color: #61dafb;
}

.content {
  display: grid;
  opacity: 0; /* Inicialmente, el contenido estará invisible */
  animation: fadeIn 1s ease-in-out forwards; /* Aplica la animación de opacidad al contenido */
}

@keyframes fadeIn {
 from {
 opacity: 0;
}
 to {
  opacity: 1;
}
}

.content img.whoweare {
  width: 200px; /* Ajusta el tamaño según tu diseño */
  height: auto;
}

.content .playButton {
  width: 50px; /* Ancho fijo */
  height: 50px; /* Altura fija */
  border-radius: 50%; /* Hacer el botón circular */
  background-color: transparent; /* Fondo transparente */
  border: none;
  cursor: pointer; /* Cambiar el cursor a mano cuando pases sobre el botón */
  display: flex; /* Usar flexbox para centrar la imagen */
  justify-content: center; /* Centrar horizontalmente */
  align-items: center; /* Centrar verticalmente */
  position: absolute; /* Utilizar posicionamiento absoluto */
  top: 50%; /* Colocar el botón en el 50% de la altura del contenedor padre */
  left: 95%; /* Colocar el botón en el 50% de la anchura del contenedor padre */
  transform: translate(-50%, -50%); /* Centrar el botón correctamente */
 }

.content .playButton img {
  max-width: 100%; /* Ancho máximo de la imagen */
  max-height: 100%; /* Altura máxima de la imagen */
  width: 80%; /* Ancho de la imagen */
  height: auto; /* Altura automática para mantener la relación de aspecto */
}

.content .playButton:hover {
  opacity: 0.5 !important;
}

.newContent {
  position: absolute;
  top: 100%;
  display: flex;
  justify-content: center; /* Centra horizontalmente el contenido */
  align-items: center; /* Centra verticalmente el contenido */
  width: 100%; /* Ajusta el ancho al 100% del contenedor principal */
 }

.videoPlayer {
  width: auto; /* Permitir que el ancho del video se ajuste automáticamente */
  height: auto; /* Permitir que la altura del video se ajuste automáticamente */
  max-width: 100%; /* Establecer un ancho máximo para evitar desbordamiento horizontal */
  max-height: 100%; /* Establecer una altura máxima para evitar desbordamiento vertical */
  display: block; /* Cambiar a bloque para permitir el centrado horizontal */
  margin: 0 auto; /* Centrar horizontalmente el video */
}`

Create a simple React app which contains an image at the center and a scrolling button that scrolls down revealing another container which is a videoplayer. It has to be centered and occupy the whole viewport once scrolled to it.

Error while toggling camera during WebRTC peer-to-peer connection: DOMException: Could not start video source

I am encountering an issue while attempting to toggle the camera during a peer-to-peer WebRTC connection. The application is built to allow users to switch between available cameras; however, upon attempting to do so, an error is thrown, specifically: “DOMException: Could not start video source”.

Here’s a snippet of the code where the error occurs:

 const handleToggleCamera = async () => {
    if (userStream) {
      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const videoDevices = devices.filter(
          (device) => device.kind === "videoinput"
        );

        // Check if there are multiple video devices available
        if (videoDevices.length > 1) {
          // Stop the existing stream
          userStream.getTracks().forEach((track) => track.stop());

          // Get the index of the current camera track
          const currentCameraIndex = videoDevices.findIndex(
            (device) => device.label === userStream.getVideoTracks()[0].label
          );

          // Calculate the index of the next camera
          const nextCameraIndex =
            (currentCameraIndex + 1) % videoDevices.length;

          // Get senders and replace the track
          const senders = peer.peer.getSenders();
          senders.forEach((sender) => {
            peer.peer.removeTrack(sender);
          });

          // Create new options for obtaining the new stream
          const options = {
            audio: true,
            video: {
              deviceId: { exact: videoDevices[nextCameraIndex].deviceId },
            },
          };

          // Obtain the new stream
          const nextStream = await navigator.mediaDevices.getUserMedia(options);

          // Apply constraints directly to the video track
          const videoTrack = nextStream.getVideoTracks()[0];
          await videoTrack.applyConstraints({
            width: { ideal: 1280 },
            height: { ideal: 720 },
          });

          // Update the local state with the new stream
          setMyStream(null); // Set to null to ensure all tracks are removed
          setMyStream(nextStream);

          // Add the new track to the peer connection
          nextStream.getTracks().forEach((track) => {
            peer.peer.addTrack(track, nextStream);
          });

          handleNegoNeeded();
        } else {
          console.error("Device does not support switching cameras.");
          // Show error message using toast or any other UI component
        }
      } catch (error) {
        console.error("Error switching camera:", error);
        console.error("Failed constraints:", error.constraints); // Log the failed constraints
      }
    }
  };

It seems that the error occurs when attempting to obtain the new stream with the updated camera. I have tried several approaches, including stopping the existing stream before obtaining the new one, but the issue persists.

I would appreciate any insights or suggestions on how to resolve this error and successfully toggle the camera during a WebRTC peer-to-peer connection. Thank you in advance for your help!

I attempted to toggle between available cameras during a WebRTC peer-to-peer connection by implementing a function handleToggleCamera() in my application. Within this function, I enumerated the available devices using navigator.mediaDevices.enumerateDevices(), filtered out video input devices, and stopped the existing stream using userStream.getTracks().forEach((track) => track.stop()). Then, I obtained the new stream with the next camera and updated it accordingly.

Expected Outcome:
I expected that upon calling handleToggleCamera(), the application would successfully switch the camera source to the next available camera without encountering any errors. The new camera stream would replace the existing one, and the peer-to-peer connection would continue seamlessly with the updated stream.

Actual Result:
Instead, upon calling handleToggleCamera(), the application threw a DOMException with the message “Could not start video source”. This error halted the camera switching process and disrupted the peer-to-peer connection. Despite trying different approaches, including ensuring the proper stopping of the existing stream before obtaining the new one, the error persisted, preventing the successful toggling of the camera.

By providing this detailed description on Stack Overflow, you’ll give potential helpers a clear understanding of what you’ve attempted, your expectations, and the issue you’re facing, which will facilitate more accurate and helpful responses.

If I only have access to a Node, how can I achieve something like Element.querySelector?

Assume you’re not able to access an Element type, only a Node type. (I have this constraint because I’m using inject(ElementRef) in Angular, but there are other cases where it might happen)

A Node instance doesn’t have a querySelector method, but it has a childNodes list property, and each of them have their own childNodes, and so on. With these, a searching algo could be implemented to find a desired Node in this Node tree, making up for the absence of querySelector.

My problem is that this seems so obvious that it sounds like it should be a native thing. Does it already exist? Or can I convert the Node to an Element so I can access the native querySelector method?

Animate chessboard pieces in Lit web component (changes between two positions)

I am creating a chess board Lit component. Basically i want to animate pieces when certain action happens.
I implemented some of these basic things like:

  • setPiece -> rerender so piece gets added and then animate
  • removePiece -> animate and then wait for ‘finish’ event to rerender and remove the piece
  • movePiece -> elements exist so i can just animate
  • clear -> animate all then remove

How do i make load function work, it basically loads new position and calculates all changes between previous and current position and then based on the change (added, removed, moved), i can create appropriate web animation.

Point is that load can have all these 3 types of animations together. So enter, exit and translations animations.
If i update instantly then exit animations won’t happen, if i wait for animations and update later, then enter won’t happen…

How do i restructure things, maybe push all animations to the piece child component or just use animate from @lit-labs/motion package which
i am not sure if it makes sense here since i am already calculating where every piece needs to move, so no need to measure things with flip technique.
I guess slapping animate directive with out: fadeOut would work but it feels dirty doing things like that with my way and directive at the same time.

Here is the playground: https://lit.dev/playground/#gist=f2759fd8b4d6df53498503ca610a6e52

Sorry if the code is bit longer, most of it are some boring conversions and few utils which you can ignore. board.ts and piece.ts are the relevant files i guess.

how to add marker variable into let latlng2

i want to add my start point(letlng2) with my live marker (red car), please help?



  function showPosition(position) {
    if (marker){
        map.removeLayer(marker);
    }
  lat = position.coords.latitude;
  lng = position.coords.longitude;
  accuracy = position.coords.accuracy  
    marker = L.marker([lat,lng],{icon: icon1}).bindPopup("Lokasi Anda").addTo(map).openPopup();
    
    let latLng2= L.latLng(lat,lng); 
    let latLng1= L.latLng(-7.849887646686694, 110.46051951389998);
   
    setInterval(() => {
      if(routingControl){
      map.removeLayer(waypoints);
    }
    routingControl= L.Routing.control({
    waypoints: [latLng2,latLng1]
  }).addTo(map);
    }, 1000);
    

  }
</script>

(https://i.stack.imgur.com/lnWR3.png)

How to set showpreview to true when using htmlembed in a custom ckeditor5 plugin?

I’m creating a custom Ckeditor5 plugin that grabs a snippet of javascript from an api and displays it. Right now when it displays in the ckeditor5 it is showing the code and not a preview of the embeded content.

In the documentation it says you can set showPreview = true however I cant find any information on how to do it within the context of the execute method.

from the documentation:

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        plugins: [ HtmlEmbed, /* ... */ ],
        toolbar: [ 'htmlEmbed', /* ... */ ],
        htmlEmbed: {
            showPreviews: true,
            sanitizeHtml: ( inputHtml ) => {
                // Strip unsafe elements and attributes, for example:
                // the `<script>` elements and `on*` attributes.
                const outputHtml = sanitize( inputHtml );

                return {
                    html: outputHtml,
                    // true or false depending on whether the sanitizer stripped anything.
                    hasChanged: true
                };
            }
        }
    } )
    .then( /* ... */ )
    .catch( /* ... */ );

this is how I am using it within my custom plugin:

export default class InsertNameCoachCommand extends Command {
execute() {
  const userInput = prompt("Please enter the username:");

  if (userInput) {
    const requestUrl = `/api/namecoach/data?  username=${encodeURIComponent(userInput)}`;

    fetch(requestUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network Response Error');
        }
        return response.json();
      })
      .then(data => {
        if (data) {
          this.editor.execute('htmlEmbed', data.embed_image);
        } else {
          console.error("Error:", data.error);
        }
      })
      .catch(error => {
        console.error("Failed to fetch data:", error);
      });
    }
  }
}```

does anyone have any experience on how to go about this?


I have added the showPreview as a param to the execute function but have been unsuccessful.

React – sort table api data on click by ascending and descending

In my React web application, I’m trying to implement a feature where when someone first clicks on a header in a specific column, that column’s API data sorts by ascending. On second click, it sorts by descending.

With the logic below, when I click on any headers, nothing happens – no sorting and no console errors. Each in the code below’s handleHeaderClick function takes in the value coming from the API.

Here’s the snippet of code where I’m trying to implement the logic, which lives inside of my “Table.tsx” component:

export const MainTable = ({ data, isLoading, error }: MainTableProps) => {

 ...

  // Sorting logic
  const rawData = data.map((group) => group.equipments).flat();
  const [tableData, setTableData] = useState(rawData);
  const [order, setOrder] = useState("ASC");

  const handleHeaderClick = (col) => {
    if (order === "ASC") {
      const sorted = [...tableData].sort((a, b) =>
        a[col].toLowerCase() > b[col].toLowerCase() ? 1 : -1
      );
      setTableData(sorted);
      setOrder("DSC");
    }
    if (order === "DSC") {
      const sorted = [...tableData].sort((a, b) =>
        a[col].toLowerCase() < b[col].toLowerCase() ? 1 : -1
      );
      setTableData(sorted);
      setOrder("ASC");
    }
  };

  ...

  return (
    <>
      <TableContainer>
        <Table variant="simple">
          <Thead>
            <Tr>
              <Th onClick={() => handleHeaderClick("manufacturer")}>
                {t("manu")}
              </Th>
              <Th onClick={() => handleHeaderClick("model")}>{t("model")}</Th>
              <Th
                onClick={() => handleHeaderClick("product-family-display-name")}
              >
                {t("desc")}
              </Th>
              <Th onClick={() => handleHeaderClick("serial-number")}>
                {t("serial")}
              </Th>
              <Th onClick={() => handleHeaderClick("state")}>{t("prov")}</Th>
              <Th onClick={() => handleHeaderClick("city")}>{t("city")}</Th>
              <Th
                onClick={() => handleHeaderClick("regular-price")}
                className="align-right"
              >
                {t("regPrice")}
              </Th>
              <Th
                onClick={() => handleHeaderClick("price")}
                className="align-right sale-header"
              >
                {t("salePrice")}
              </Th>
            </Tr>
          </Thead>
          <Tbody>
            {currentPageData.map((equipment: Equipment) => (
              <Tr key={equipment.id}>
                <Td>
                  {equipment.manufacturer.length > 0
                    ? equipment.manufacturer
                    : "N/A"}
                </Td>
                <Td>{equipment.model.length > 1 ? equipment.model : "N/A"}</Td>
                <Td>{equipment["product-family-display-name"]}</Td>
                <Td>{equipment["serial-number"]}</Td>
                <Td>{equipment.state}</Td>
                <Td>
                  <a
                    target="_blank"
                    href={`https://website.com/locations/${
                      equipment.city.indexOf(" ")
                        ? equipment.city.replace(/s/g, "-")
                        : equipment.city
                    }`}
                  >
                    {equipment.city}
                  </a>
                </Td>
                <Td className="align-right reg-price">
                  {formatPrice(Number(equipment["regular-price"]?.text))}
                </Td>
                <Td className="align-right sale-price">
                  <strong>
                    {formatPrice(Number(equipment["price"]?.text))}
                  </strong>
                </Td>
              </Tr>
            ))}
          </Tbody>
        </Table>
      </TableContainer>
    </>
  );
};

Next.JS Middleware routing

I’m checking for the role and logged-in users to redirect them but it seems the middleware is not working correctly
this is my middleware.ts :

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { isAuth } from "@/utils/isAuth";
import { isAdmin } from "@/utils/isAdmin";

export function middleware(request: NextRequest) {
  const auth = isAuth();

  if (!auth) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  const admin = isAdmin();

  if (!admin) return NextResponse.redirect(new URL("/posts", request.url));

  return NextResponse.next();
}

export const config = {
  matcher: "/dashboard",
};

but it seems the isAuth and isAdmin are not working!

this is the isAuth :

export function isAuth() {
  const authToken = sessionStorage.getItem("authToken");

  if (!authToken) return false;

  
  return true;
}

and this is isAdmin:

import jwt from "jsonwebtoken";

export function isAdmin() {
  const authToken = sessionStorage.getItem("authToken");

  if (authToken) {
    try {
      const decodedToken = jwt.decode(authToken);

      if (
        decodedToken &&
        typeof decodedToken === "object" &&
        "role" in decodedToken
      ) {
        return decodedToken.role === "admin" || decodedToken.role === "developer";
      }
    } catch (error) {
      return false;
    }
  }

  return false;
}

i tried to use async for decode but didn’t work.

TypeError: databaseRef.child is not a function, while saving data to the realtime database in the react project

I have created an react project, here is the code:-

AuthContext.js:-

       import { useContext, createContext, useEffect, useState } from 'react';
    import {
      GoogleAuthProvider,
      signInWithPopup,
      signInWithRedirect,
      signOut,
      onAuthStateChanged,
    } from 'firebase/auth';
    import { auth, databaseRef } from '../firebase'; 

    const AuthContext = createContext();

    export const AuthContextProvider = ({ children }) => {
      const [user, setUser] = useState({});

      const googleSignIn = async () => {
        const provider = new GoogleAuthProvider();
        try {
          const result = await signInWithPopup(auth, provider);
          return result;
        } catch (error) {
          console.error('Error during sign-in:', error);
        }
      };

      const logOut = async () => { // Make logOut async for potential errors
        try {
          await signOut(auth);
        } catch (error) {
          console.error('Error signing out:', error);
        }
      };

      useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
          setUser(currentUser);
          console.log('User', currentUser);
        });

        return unsubscribe;
      }, []);

      return (
        <AuthContext.Provider value={{ googleSignIn, logOut, user, databaseRef }}>
          {children}
        </AuthContext.Provider>
      );
    };

export const UserAuth = () => {
  return useContext(AuthContext);
};

Account.jsx:-

import React, { useEffect, useState } from 'react';
import { UserAuth } from '../context/AuthContext';
import Navbar from '../components/Navbar';

const Account = () => {
  const { user, databaseRef } = UserAuth();
  const [userIds, setUserIds] = useState([]);

  useEffect(() => {
    const fetchUserIds = async () => {
      const snapshot = await databaseRef.child('userids').once('value');
      const data = snapshot.val();
      setUserIds(Object.values(data || {}));
    };

    fetchUserIds();
  }, []);

  return (
    <div className='container'>
      <Navbar url='/signin' text='Log out' />
      <div className='w-[300px] m-auto'>
        <h1 className='text-center text-2xl font-bold pt-12'>Account</h1>
        <div>
          <p>Welcome, {user?.displayName}</p>
          {userIds.length > 0 && (
            <ul>
              {userIds.map((id) => (
                <li key={id}>{id}</li>
              ))}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
};

export default Account;

Signin.jsx:-

 import React, { useEffect } from 'react';
import { GoogleButton } from 'react-google-button';
import { UserAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import Navbar from '../components/Navbar';

const Signin = () => {
  const { googleSignIn, user, databaseRef } = UserAuth();
  const navigate = useNavigate();

  const handleGoogleSignIn = async () => {
    try {
      const result = await googleSignIn();
      const userObj = result.user;

      const userId = userObj.uid;
      console.log('Attempting to save user ID:', userId); // Log before saving
      await databaseRef.child('userids').push(userId);
      console.log('User ID saved successfully:', userId);

  navigate('/account');
    } catch (error) {
      console.error('Error during sign-in or saving user ID:', error);
    }
  };

   useEffect(() => {
     if (user != null) {
       // navigate('/account');
     }
   }, [user]);

  return (
    <div>
      <Navbar url='/' text='Home' />
      <h1 className='text-center text-3xl font-bold py-8'>Sign in</h1>
      <div className='max-w-[240px] m-auto py-4'>
        <GoogleButton onClick={handleGoogleSignIn} />
      </div>
    </div>
  );
};

export default Signin;

firebase.js:-

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase, ref } from 'firebase/database';

// TODO: Add SDKs for Firebase products that you want to use
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "QIazSyDO132QtFu798QoI472h6pb2KzdXZExyQs",
  authDomain: "trail-24.firebaseapp.com",
  databaseURL: "https://trail-24-default-rtdb.firebaseio.com",
  projectId: "trail-24",
  storageBucket: "trail-24.appspot.com",
  messagingSenderId: "1011673947249",
  appId: "1:1011943747984:web:08ee8dd634ffe87c55f915",
  measurementId: "G-FSXIJTC9PX"
};


const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
const db = getDatabase(app);
export const databaseRef = ref(db);

This is the console log:-

   Attempting to save user ID: RdMQaBouH2RY5rVozaw5b9dSAro1

Signin.jsx:23 Error during sign-in or saving user ID: TypeError: databaseRef.child is not a function
at Object.handleGoogleSignIn [as onClick] (Signin.jsx:18:1)

Firebase Database rules:-

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

I am new to react and I have already tried different ways to save this data in the realtime database of firebase, but I am successfully login the user but I am unable to save the data, I am got to the position from where the process of saving the data has been initialized but it is not saving the data, there is some problem while creating the dataref.child().

Someone please help me.

React hook form: property in class get as undefined

I have class with static property and function, and when I pass function to validate property in React hook form registry function then I get error:

Validator.ts:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘phoneRegex’)

Class:

type validatorResponse = string | boolean

class Validator {
    private static readonly emailRegex: RegExp = /^[w-.]+@([w-]+.)+[w-]{2,4}$/
    private static readonly phoneRegex: RegExp = /^[+]?[(]?[0-9]{3}[)]?[-s.]?[0-9]{3}[-s.]?[0-9]{4,6}$/
    private static readonly lettersRegex: RegExp = /^[A-Za-z]+$/
    private static readonly fullnameRegex: RegExp = /(^[A-Za-z]{3,16})([ ]{0,1})([A-Za-z]{3,16})?([ ]{0,1})?([A-Za-z]{3,16})?([ ]{0,1})?([A-Za-z]{3,16})/

    static getLetter() {
        return this.lettersRegex
    }

    public static email(value: string): validatorResponse {
        if (!(this.emailRegex.test(value))) {
            return "Invalid email"
        }
        return true
    }

    public static phone(value: string): validatorResponse {
        if (!(this.phoneRegex.test(value))) {
            return "Invalid format of phone number"
        }
        return true
    }

    public static letters(value: string): validatorResponse {
        if (!(/^[A-Za-z]+$/.test(value))) {
            return "Use only letters"
        }
        return true
    }

    public static fullname(value: string): validatorResponse {
        if (!(this.fullnameRegex.test(value))) {
            return 'Invalid fullname'
        }
        return true
    }
}

export default Validator

and registry example:

<input className="form-input" {...register("lastname", {
                                    required: true,
                                    validate: Validator.letters
                                })} type="text" />

Well, I firstly though that’s cause regex, but checked and that cause with all types. By now I just declare regex inside function, but I would like know what that’s cause and how fix this

D3 How to use FontAwesome icons

I would like to use the icon from FotnAwesome and append it to my g tag. As described here, I tried, but it doesn’t work.

Does anyone have a hint?
I use d3.v7.js.

                             
            const svg = d3.select("#chart-area")
                        .append("svg") 
                            .attr("width", 800)  
                            .attr("height", 400) 
            
const g = d3.select("svg").append("g")
                            .attr('transform', `translate(10,20)`)

          g.append('text')
                        .attr('font-size', '12px')
                        .attr('font-family', 'FontAwesome')
                        .text('uf118')
<script src="https://d3js.org/d3.v7.js" charset="utf-8"></script>
<div id="chart-area"></div>