Mouse over event only working on one card

enter image description here

I’m using a mouse over event to have the shadows change from black to pink. However, when I add the mosue over event onto the other cards they only change the first card. How to I get each indivual card to change colour when hovered?

JS

<script>
    function mouseOver() {
        document.getElementById("CardHover").style.boxShadow = "-6px 6px 0px 0px #FF8A88";
    }
    
    function mouseOut() {
        document.getElementById("CardHover").style.boxShadow = "-6px 6px 0px 0px #000";
    }
    </script>

HTML

<div class="report" id="CardHover" onclick="location.href='#';" onmouseover="mouseOver()" onmouseout="mouseOut()">
            <img style="width: 100%; height: 100%; border-radius: 10px;" src="#.png" alt="">
            <div style="display: flex; flex-direction: column; align-items: flex-start; gap: 6px; padding: 8px;">
                <h6>#ServiceDesign  #DesignThinking  #Ethnography</h6>
                <h4>Title</h4>
                <p>Body Copy</p>
                <a href="#" class="tertiary">Explore</a>
            </div>
        </div>

<div class="report" id="CardHover" onclick="location.href='#';" onmouseover="mouseOver()" onmouseout="mouseOut()">
            <img style="width: 100%; height: 100%; border-radius: 10px;" src="#.png" alt="">
            <div style="display: flex; flex-direction: column; align-items: flex-start; gap: 6px; padding: 8px;">
                <h6>#ServiceDesign  #DesignThinking  #Ethnography</h6>
                <h4>Title</h4>
                <p>Body Copy</p>
                <a href="#" class="tertiary">Explore</a>
            </div>
        </div>

Expectng to have each card have it’s own hover using mosue over events.

passing data in react from a child component up through the parent

I am a beginner and i have a structure like this:

<CountContext.Provider value={{ contextCount, setContextCount }}>
        <Wrapper />
        <Bar />
 </CountContext.Provider>

Inside the wrapper I have 12 cards, each with a click counter.
The bar contains a counter of all clicks, implemented through the context, as well as a reset button.
How can I, without using third-party libraries, reset not only the general counter, but also reset each individual counter on the cards?

I try useEffect, context, if-else, conditional render and some other ways.

How can I instrument a function using OpenTelemetry and SvelteKit

Context

I am using SvelteKit and would like to instrument it with Otel. I have tried using the NodeSDK for automatic instrumentation and it works; I am able to see some automatically created traces in my Grafana Tempo backend, but they aren’t very useful.

Question

I specifically want to instrument some functions in my +page.svelte files or my components (which may run on either the client or the server) so that they clearly show up as their own traces.

Is anyone able to tell me how I can manually instrument a function inside a +page.svelte file so it is the first span in a trace? (My attempt at getting this to work is in the +page.svelte file in the gist)

Code

Here is the gist with my current code.

Extra context

The following is an exerpt from the linked gist to show the code I’d love to work. I’d expect this to show up in Grafana Tempo as a trace called getContactsAndUpdateStore, but I don’t see this trace, only the automatically generated ones.

    async function getContactsAndUpdateStore(userId: string) {
        const tracer = opentelemetry.trace.getTracer('default');
        console.log(tracer);
        return tracer.startActiveSpan('getContactsAndUpdateStore', async (span) => {
            try {
                span.setAttribute('userId', userId);
                const users = await getContacts(userId);
                contacts.set(users);
                span.addEvent('Contacts fetched successfully');
            } catch (error) {
                console.error('Error fetching contacts:', error);
                if (error instanceof Error) {
                    // Record the exception in the span if it's an Error
                    span.recordException(error);
                    span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
                } else {
                    // If it's not an Error instance, stringify if possible.
                    span.setStatus({ code: SpanStatusCode.ERROR, message: String(error) });
                }
                contacts.set([]); // Fallback in case of error
            } finally {
                console.log(span);
                span.end();
                console.log(span);
            }
        });
    }

console.log(tracer) produces:
tracer

console.log(span) produces:
span

I tried using auto-instrumentations-web as well, but whenever I imported it I got an issue and was unable to get it working. However I have a suspicison that I somehow need to handle getting the tracer differently depending on whether the code is running on the client or server, however I’m a bit out of my depth here and would sincerely appreciate any help!

How can i make my particles act more like a fluid

I am trying to create a fluid simulation using sph in javascript i have finally calculated everything so the particles receive a force but the force doesnt seem to work properly and just pushes the particles away from each other randomly because when i add gravity it just goes to to mayhem

My result ideally would be without gravity the particles are evenly distributed without clumps and massive gaps and with gravity it should not explode and flow back and forth

i am using vector2js by ronenness

var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 100;
var simMinWidth = 20.0;
var cScale = Math.min(canvas.width, canvas.height) / simMinWidth;
var simWidth = canvas.width / cScale;
var simHeight = canvas.height / cScale;
var numParticles = 100;
var radius = 0.2;
var pressuremultiplier = 10
var restdensity = 1

function cX(position){
    return position.x * cScale;
}

function cY(position){
    return position.y * cScale;
}

class Particle{
    constructor(x,y){
        this.position = new Vector(x,y)
        this.velocity = new Vector(0,0);
        this.radius = radius;
        this.smoothinglength = 6*radius
        this.density = 1
        this.pressure = 1
        this.pressureforce = 1
        this.mass =1
    }
    updateAcceleration(){
      this.calculatedensity(fluidSimulator.particles)
      this.calculatepressure()
      this.calculatepressureforce(fluidSimulator.particles);
      this.acceleration = (this.pressureforce.divScalar(this.density)).add(fluidSimulator.gravity);
   
    }
    checkboundarys(){
      if (this.position.x - this.radius < 0.0) {
        this.position.x = 0.0 + this.radius;
        this.velocity.x = -fluidSimulator.collisionDamping*this.velocity.x;
      }
    
      if (this.position.x + this.radius > simWidth) {
          this.position.x = simWidth - this.radius;
          this.velocity.x = -fluidSimulator.collisionDamping*this.velocity.x;
      }
      
      if (this.position.y - this.radius < 0.0) {
          this.position.y = 0.0 + this.radius;
          this.velocity.y = -fluidSimulator.collisionDamping*this.velocity.y;
      }
      
      if (this.position.y + this.radius > simHeight) {
          this.position.y = simHeight - this.radius; // Adjusted this line
          this.velocity.y = -fluidSimulator.collisionDamping*this.velocity.y;
      }
    }
    calculatedensity(nearbyparticles){
      let density = 0;
      for (let cparticle of nearbyparticles){
        if (cparticle != self){
          let distance = this.position.distanceFrom(cparticle.position);
          density += cparticle.mass * fluidSimulator.poly6kernel(distance,this.smoothinglength)
        }
      }
      this.density = density;
    }
    calculatepressure(){
      this.pressure = pressuremultiplier*(this.density-restdensity)
    }
    calculatepressureforce(nearbyparticles) {
      let pressureforce = new Vector(0, 0);
      let pressuremagnitude = 0;
      for (let cparticle of nearbyparticles) {
        let distance = this.position.distanceFrom(cparticle.position);
        if (distance !== 0) {
          let directionvector = new Vector((this.position.x-cparticle.position.x)/distance,(this.position.y-cparticle.position.y)/distance);
          
          // Check if the denominator (cparticle.density) is not zero
          if (cparticle.density !== 0) {
            pressuremagnitude = cparticle.pressure * cparticle.mass * fluidSimulator.spikykernelderrivative(distance, this.smoothinglength) / cparticle.density;
            pressureforce.x += directionvector.x*(pressuremagnitude);
            pressureforce.y += directionvector.y*(pressuremagnitude)
            if (distance < this.smoothinglength){
              //console.log(pressureforce)
            }
          }
        }
      }
      this.pressureforce = pressureforce.mulScalar(-1);
    }
    
    simulateParticle(){
        this.updateAcceleration();
        this.velocity = this.velocity.add(this.acceleration.mulScalar(fluidSimulator.timestep));
        this.position = this.position.add(this.velocity.mulScalar(fluidSimulator.timestep));
        this.checkboundarys()
        
    }

}

class SPHFluidSimulator{
    constructor(){
        //simulation constants
        this.timestep = 1/30;
        this.gravity = new Vector(0,0);
        this.collisionDamping = 1;
        this.particleSpacing = 0.1;
        this.particles = [];
        


    }
    poly6kernel(r,h){
      let influence = 0
      if ( r>= 0 & r<= h ){
        influence = (h**2 - r**2)**3

      }
      return (315/(64*Math.PI*h**9))*influence
  
    }
    spikykernelderrivative(r,h){
      let influence = 0
      if (r>= 0 & r<= h){
        influence = -3*(h-r)**2
      }
      return (15/(Math.PI*h**6))*influence
  

    }
    initialiseParticle(particle) {
        // Add a particle to the simulation and update the grid
        this.particles.push(particle);
    }

    
}

function generateParticlesRandom() {
    for (let i = 0; i < numParticles; i++) {
        let particleX = Math.random() * simWidth;
        let particleY = Math.random() * simHeight;
        let particle = new Particle(particleX, particleY);
        fluidSimulator.initialiseParticle(particle);
    }
}

function physics(){
    for (const particle of fluidSimulator.particles){
        particle.simulateParticle();
    }
  //console.log(fluidSimulator.particles[0])

}
function draw(){
    
  c.clearRect(0, 0, canvas.width, canvas.height);
  c.fillStyle = "#005EB8";
  for (let i=0; i < numParticles; i++){
    let particle = fluidSimulator.particles[i];
    c.beginPath();  
    c.arc(cX(particle.position), cY(particle.position), cScale *radius, 0.0, 2.0 * Math.PI); 
    c.closePath();
    c.fill();       
  };        
}

function simulate(){
    physics();
    draw();
    requestAnimationFrame(simulate);
}

var fluidSimulator = new SPHFluidSimulator();
generateParticlesRandom();
simulate();

Inconsistent EventBridge Rule Execution In AWS: Seeking Guidance For Ensuring Proper Intervals In API Calls”

I’ve configured an EventBridge rule in AWS to trigger an API call every 3 hours, and I’ve implemented logging to monitor these calls in CloudWatch. However, I’ve noticed inconsistent behavior in the intervals, with occurrences at 2 hours, 4 hours, or even multiple times within a minute. Could you provide insights into why this variability is happening, and how I can ensure a consistent 3-hour interval between API calls?

Despite creating multiple EventBridge rules to trigger a specific API call every 3 hours, the execution remains inconsistent. The expectation is that the API call should occur precisely after 3 hours, yet the observed behavior includes variations in intervals, such as calls at 2 hours, 4 hours, or even multiple times within a minute. Seeking assistance to troubleshoot and achieve a stable 3-hour interval for the API calls.

how to append and replace word to another word in textarea from custom-context-menu, JavaScript

Change one word to another When active on a word, the word exists in an array
The words in the textare If they are not in the array at the same time
Context menu not active on all word, included a link to change one word to another
But the problem is that it doesn’t work in the textarea you can help me fixed worked on textarea
codepen contextmenu

I’ve been looking for that for a long time how can I For a word that has textarea the custom context menu opened the word should be specific have in the array to recognize him Can anyone help me. That’s just an example of a context menu, not in a textarea if textarea value does not have specificwords word It shouldn’t be open The code I put as a suggestion for my request has nothing to do with the source

var specificwords = [‘hi’, ‘hello’, ‘yo’, ‘hey’, ‘some’, ‘howdy’];

let textarea = document.getElementsByTagName("textarea")[0];
let contextMenu = document.getElementsByClassName("custom-context-menu")[0];
specificwords = ['hi', 'hello', 'yo', 'hey', 'some', 'howdy'];
contextMenu.setAttribute("open", true);

textarea.oncontextmenu = (event) => {
    event.preventDefault();

    let string = event.target.value;
    let words = string.split(' ');
    let result = words.filter(word => specificwords.includes(word))

    if (result.length > 0) {
        let x = event.pageX, y = event.pageY;
        contextMenu.style.left = x + "px";
        contextMenu.style.top = y + "px";
        contextMenu.style.display = "block";

        contextMenu.classList.add("on");
    }
}

document.onclick = (event) => {
    if (contextMenu.classList.contains("on")) {
        contextMenu.classList.remove("on");
        contextMenu.style.display = "none";
    }
}
.custom-context-menu {
    z-index: 1100;
    display: none;
    position: absolute;
    list-style: none;
    margin: 0;
    padding: 0;
    border: 1px solid black;
    background: white;
}

.custom-context-menu li {
    padding: 5px;
    cursor: pointer;
}

.custom-context-menu li:hover {
    background-color: aqua;
}
<!DOCTYPE html>
<head>
    <link href="./main.css" rel="stylesheet"/>
</head>
<body>
    <textarea>hello This is some text. Click on any word and then do right click</textarea>
    <ul class="custom-context-menu">
        <li>rule</li>
        <li>slde</li>
        <li>rebaz</li>
    </ul>
</body>
<script src="./main.js" type="text/javascript"></script> </html>

NodeJS i can’t import any module without changing script type to module

My HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="index.css" rel="stylesheet">
    <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-database.js"></script>
    <script src="index.js"></script>
    <title>TunaChat</title>
</head>
...
</html>

My JS

import AOS from "./node_modules/aos"
import "./node_modules/aos/dist/aos.css"
AOS.init()

when i run this code it throws a error to console
Uncaught SyntaxError: Cannot use import statement outside a module

I tried to add type=”module” to my script
<script src="index.js" type="module"></script>

Result:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/css". Strict MIME type checking is enforced for module scripts per HTML spec.

Also i tried to add type=”module” to package.json file

{
  "name": "tunachat",
  "version": "0.2.1",
  "description": "",
  "main": "index.html",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Sublimieren-Haupt",
  "license": "ISC",
  "dependencies": {
    "aos": "^2.3.4"
  }
}

Result:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/css". Strict MIME type checking is enforced for module scripts per HTML spec.

So Firebase CDN and AOS conflict with each other because i am using type=”module”

I am trying to get AOS working.

useEffect render previous value, instead new setState

Im trying to set set an IP address into “” and (last queried value).
But its always render same state and render new state after second render.
I know its because of setState syncronomous behaviour. I have been trying to put timeout and declare indirect value to make it works, but none of these succeed.

**///DECLARED VALUE/////**
  const [ip, setIp] = useState("");
  const [isValid, setIsValid] = useState(true);
  const [buttonActive, setButtonActive] = useState(false);
  const [ipV4Completed, setIpV4Completed] = useState(false);

  const [savedIp, setSavedIp] = useState("");
  const [location, setLocation] = useState("");
  const [isp, setIsp] = useState("");
  const [ipV4, setIpV4] = useState(true);

  const [savedData, setSavedData] = useState("")

  let storageData = JSON.parse(localStorage.getItem("savedData")) || [];

  const onInputChange = (data) => {
    setIp(data.target.value);
    validateInput(data);
  };

  const validateInput = (e) => {
    const ipV4Regex = /^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?b){4}$/;
    const ipV6Regex = /^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/i;
    let { value } = e.target;

    if (value.match(ipV4Regex)) {
      setIsValid(true);
      setButtonActive(true);
      setIpV4(true);
    } else if (value.match(ipV6Regex)) {
      setIsValid(true);
      setButtonActive(true);
      setIpV4(false);
    } else if (value === "") {
      setIsValid(true);
      setButtonActive(false);
    } else {
      setIsValid(false);
      setButtonActive(false);
    }
  };

**///FUNCTION THAT RETURN SUPPOSED VALUE/////**
  const proceedInput = useCallback(() => {
    console.log('proceedInput called with ip:', ip);
    axios
      .get(
        `https://geo.ipify.org/api/v2/country,city?apiKey=${process.env.REACT_APP_KEY_APIFY}&ipAddress=${ip}`)
      .then((response) => {
        setSavedIp(response.data.ip);
        setLocation(response.data.location);
        setMapLocation(response.data.location);
        setIsp(response.data.isp);

        const ipExist = storageData.some(item => item.ip === response.data.ip);

        if (!ipExist) {
          storageData.push(response.data);
          setSavedData(storageData);
        }
        
        if (ipV4) {
          setIpV4Completed(true);
        } else {
          setIpV4Completed(false);
        };

      })
      .catch((error) => {
        console.error("Failed to fetch location data:", error);
      });
  }, [ip]);

**///BLOCK WHERE USESTATE NOT DIRECTLY UPDATED/////**
  useEffect(() => {
    if (currentLocation){
      setIp("")
      proceedInput();
    }
  }, [currentLocation])

**///BLOCK WHERE USESTATE NOT DIRECTLY UPDATED/////**
  useEffect(() => {
    if (historyLocation){
      setIp(historyLocation.ip)
      proceedInput();
    }
  }, [historyLocation])

  useEffect(() => {
    if (savedData){
      localStorage.setItem("savedData", JSON.stringify(savedData));
    }
  }, [savedData])

React Native Firebase Authentication On Cold Start

I am running a react native app v0.72 and am using an emulator for ios.

I am having some issues from cold start of my app gathering currentUser. Any reading online is indicating this is not available on cold start. I simply tried cheating this by implementing a 15 second delay on my app start potentially to listen for auth state changes, presuming it would only take a few seconds to generate a new token. I am unable to get the user object to have a .currentUser value after x period of time. Not really sure what the issue is here. I see auths hitting my firebase console so I know i’m signed in. I have a concern maybe the persistence isn’t’ working properly for firebase specifically. I actually store things like an email after sign in in async storage.

Here is my code that i’m using and the flow its following: My user launches the app, they navigate to my “SplashScreen.js” if they don’t have an ‘auth’ session already after x amount of time. I am signing in via apple, i get my apple oauth token back, and a firebase token as well indicating i’m logged in, it navigates me to my “HomeScreen.js”. I force close the apple app and relaunch. Then I wait again 15 seconds and i’m seeing NULL in the currentUser and i’m back at the “SplashScreen.js” because i did not authenticate in time.

Here all the major files involved (altered some files that may have sensitive like information in it so its not my true sensitive data in those spots):

App.tsx (see this referred to as app.js as well or index.js, also wondering if its worth updating this name of this file because this is what react native provides my default on init)???

import { auth } from './configs/Firestore';
import 'react-native-gesture-handler';
import React, { useEffect, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { View, ActivityIndicator } from 'react-native';

// Import auth object from Firestore configuration
import { getAuth, onAuthStateChanged, onIdTokenChanged } from 'firebase/auth';


// Screens
import SplashScreen from './screens/SplashScreen';
import SignupScreen from './screens/CreateAccountScreen';
import LoginScreen from './screens/LoginScreen';
import InitialAccountConfigurationScreen from './screens/InitialAccountConfigurationScreen';
import ForgotPasswordScreen from './screens/ForgotPasswordScreen';
import TermsAndConditionsScreen from './screens/TermsAndConditionsScreen';
import PrivacyScreen from './screens/PrivacyPolicyScreen';
import HomeScreen from './screens/HomeScreen';
import ExerciseHomeScreen from './screens/ExerciseHomeScreen';
import CreateCustomWorkoutScreen from './screens/CreateCustomWorkoutScreen';
import FinalizeCreateCustomWorkoutScreen from './screens/FinalizeCreateCustomWorkoutScreen';
import EditCustomWorkoutNamesScreen from './screens/EditCustomWorkoutNamesScreen';
import EditCustomWorkoutDetailsScreen from './screens/EditCustomWorkoutDetailsScreen';
import AddOneExerciseScreen from './screens/AddOneExerciseScreen';
import StartExerciseNamesScreen from './screens/StartExerciseNamesScreen';
import StartExerciseWorkoutScreen from './screens/StartExerciseWorkoutScreen';
import PreviousCompletedWorkoutNamesScreen from './screens/PreviousCompletedWorkoutNamesScreen';
import PreviousCompletedWorkoutDetailsScreen from './screens/PreviousCompletedWorkoutDetailsScreen';
import HelpHomeScreen from './screens/HelpHomeScreen';
import SendFeedbackScreen from './screens/SendFeedbackScreen';
import SettingsScreen from './screens/SettingsScreen';
import EditProfileScreen from './screens/EditProfileScreen';
import ChangePasswordScreen from './screens/ChangePasswordScreen';
import DeleteAccountScreen from './screens/DeleteAccountScreen';

const Stack = createStackNavigator();

const App = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [initialLoadingComplete, setInitialLoadingComplete] = useState(false);

  // Function to create a delay
  const delay = ms => new Promise(res => setTimeout(res, ms));

  
  useEffect(() => {
    console.log("App started, setting up auth listener");
  
    const unsubscribe = onIdTokenChanged(auth, async (user) => {
      console.log("Auth State Changed");
      console.log("User from Listener:", user);
      console.log("CurrentUser from Auth:", auth.currentUser);
  
      if (user) {
        setIsAuthenticated(true);
        const idToken = await user.getIdToken();
        console.log("Firebase ID Token:", idToken);
      } else {
        setIsAuthenticated(false);
        console.log("No user found, retrying in 5 seconds");
        setTimeout(() => {
          console.log("Retry CurrentUser from Auth:", auth.currentUser);
        }, 5000);
      }
      setIsLoading(false);
    });
  
    // Start the forced 15 seconds delay
    delay(10000).then(() => setInitialLoadingComplete(true));
  
    // Cleanup function
    return () => unsubscribe();
  }, []);
  
  

  if (isLoading || !initialLoadingComplete) {
    return (
      <View style={{ flex: 1, backgroundColor: '#123456', justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" color="#FFFFFF" />
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#323232' }}>
      <NavigationContainer>
        <Stack.Navigator
          initialRouteName={isAuthenticated ? 'Home' : 'Splash'}
          screenOptions={{ cardStyle: { backgroundColor: '#323232' } }}
        >
          <Stack.Screen name="Splash" component={SplashScreen} />
          <Stack.Screen name="Signup" component={SignupScreen} />
          <Stack.Screen name="Login" component={LoginScreen} />
          <Stack.Screen name="InitialAccountConfiguration" component={InitialAccountConfigurationScreen} />
          <Stack.Screen name="ForgotPassword" component={ForgotPasswordScreen} />
          <Stack.Screen name="TermsAndConditions" component={TermsAndConditionsScreen} />
          <Stack.Screen name="Privacy" component={PrivacyScreen} />
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="ExerciseHome" component={ExerciseHomeScreen} />
          <Stack.Screen name="CreateCustomWorkout" component={CreateCustomWorkoutScreen} />
          <Stack.Screen name="FinalizeCreateCustomWorkout" component={FinalizeCreateCustomWorkoutScreen} />
          <Stack.Screen name="EditCustomWorkoutNames" component={EditCustomWorkoutNamesScreen} />
          <Stack.Screen name="EditCustomWorkoutDetails" component={EditCustomWorkoutDetailsScreen} />
          <Stack.Screen name="AddOneExercise" component={AddOneExerciseScreen} />
          <Stack.Screen name="StartExerciseNames" component={StartExerciseNamesScreen} />
          <Stack.Screen name="StartExerciseWorkout" component={StartExerciseWorkoutScreen} />
          <Stack.Screen name="PreviousCompletedWorkouts" component={PreviousCompletedWorkoutNamesScreen} />
          <Stack.Screen name="PreviousCompletedWorkoutDetails" component={PreviousCompletedWorkoutDetailsScreen} />
          <Stack.Screen name="HelpHome" component={HelpHomeScreen} />
          <Stack.Screen name="SendFeedback" component={SendFeedbackScreen} />
          <Stack.Screen name="Settings" component={SettingsScreen} />
          <Stack.Screen name="EditProfile" component={EditProfileScreen} />
          <Stack.Screen name="ChangePassword" component={ChangePasswordScreen} />
          <Stack.Screen name="DeleteAccount" component={DeleteAccountScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </View>
  );
};

export default App;

Firestore.js

import { initializeApp } from 'firebase/app';
import { getApp } from 'firebase/app';
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from 'firebase/firestore';
import { getAuth, setPersistence, browserSessionPersistence } from 'firebase/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getReactNativePersistence } from 'firebase/auth/react-native';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';

const storage = getReactNativePersistence(ReactNativeAsyncStorage)
//const app = getApp();

const firebaseConfig = {
    apiKey: "AIzaSyCu2EX4S7_123_sOo8",
    authDomain: "xaza-health.firebaseapp.com",
    projectId: "xaza-health",
    storageBucket: "xaza-health.appspot.com",
    messagingSenderId: "116553309985",
    appId: "1:116553308885:web:cce248380cc9e89a3e05c",
    measurementId: "G-HV50L9NTPE",
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

console.log(auth);

// Set persistence
setPersistence(auth, getReactNativePersistence(AsyncStorage))
  .then(() => {
    console.log('Persistence set to React Native AsyncStorage');
  })
  .catch((error) => {
    console.error('Error setting persistence:', error);
  });

export { auth };

SplashScreen.js



import React, { useState, useRef, useEffect } from 'react';
import { View, Text, Platform, Animated, SafeAreaView, Image, TouchableOpacity, StyleSheet, Button } from 'react-native';
import { Path, Svg } from 'react-native-svg';
import DeviceInfo from 'react-native-device-info';
import AsyncStorage from '@react-native-async-storage/async-storage';
import EncryptedStorage from 'react-native-encrypted-storage';


// Security
import CheckVersion from '../security/CheckVersion';
import CheckSessionLoggedInAlready from '../security/CheckSessionLoggedInAlready';
import CheckSessionNotLoggedIn from '../security/CheckSessionNotLoggedIn';  // Adjust the path as necessary

// Custom Headers
import BlankHeader from '../headers/HeaderBlank';
// Custom Styles
import stylesSplashScreen from '../styles/StylesSplashScreen';
// Custom Buttons
import CustomButtonEnabled from '../buttons/CustomButtonEnabled';
import AppleSignInButton from '../buttons/AppleSignIn'; 
import GoogleSignInButton from '../buttons/GoogleSignIn'; 
// Custom Modals
import GeneralMessageModal from '../modals/GeneralMessageModal';
import GeneralMessageNoButtonsModal from '../modals/GeneralMessageNoButtonsModal';
// Firebase / OAuth
import { auth } from '../configs/Firestore'; 
import { getAuth, GoogleAuthProvider, signInWithCredential, OAuthProvider } from 'firebase/auth';
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import { appleAuth } from '@invertase/react-native-apple-authentication';


const AnimatedPath = Animated.createAnimatedComponent(Path);

const SplashScreen = ({ navigation }) => {
  const { shouldUpdateApp, errorMessage, setErrorMessage } = CheckVersion();
  //const { sessionUserProvider, sessionUserEmail, sessionUserUsername, sessionUserFirstName, sessionUserFirebaseUID, sessionDataIsLoaded } = CheckSessionLoggedInAlready(navigation);


  



  const [generalMessageModalVisible, setGeneralMessageModalVisible] = useState(false);
  const [generalMessageModalData, setGeneralMessageModalData] = useState({ title: '', message: '' });

  const [loggedIn, setloggedIn] = useState(false);
  const [userInfo, setuserInfo] = useState([]);

  const [isSigninInProgress, setIsSigninInProgress] = useState(false);

  const handleAppleSignIn = async () => {
    console.log("Signing in with Apple");
    try {
      // Start Apple Sign-In Request
      const appleAuthResponse = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
      });
  
      // Check credential state
      const credentialState = await appleAuth.getCredentialStateForUser(appleAuthResponse.user);
  
      if (credentialState === appleAuth.State.AUTHORIZED && appleAuthResponse.identityToken) {
        // User is authenticated and token received
        console.log('Apple SignIn Success:', appleAuthResponse);
  
        // Create Firebase credential
        const provider = new OAuthProvider('apple.com');
        const credential = provider.credential({
          idToken: appleAuthResponse.identityToken,
          rawNonce: appleAuthResponse.nonce
        });
  
        // Sign in to Firebase with the Apple credential
        const firebaseUserCredential = await signInWithCredential(auth, credential);
  
        if (firebaseUserCredential) {
          console.log('Firebase user', firebaseUserCredential.user);
          console.log("Firebase User after Sign-in:", auth.currentUser);
          const firebaseUser = firebaseUserCredential.user;
          // Log the providerData array to inspect if the email is there
          console.log('Provider Data:', firebaseUser.providerData);

          // Extract the provider ID
          const providerId = firebaseUser.providerData.find((data) => data.providerId === 'apple.com')?.providerId || 'apple.com';

          // If firebaseUser.email is undefined, try to get the email from providerData
          const emailFromProviderData = firebaseUser.providerData
            .filter((pd) => pd.providerId === 'apple.com' && pd.email)
            .map((pd) => pd.email)[0];

          // Use email from providerData if available
          const emailToUse = firebaseUser.email || emailFromProviderData;

          // Call postSignIn with the defined email, uid and providerId.
          await postSignIn({
            email: emailToUse, // Use the potentially fallback email
            firebaseuid: firebaseUser.uid,
            provider: providerId,
          });
        }
      } else {
        console.log("User not authorized or Identity token missing");
      }
    } catch (error) {
      console.log('Error with Apple Sign-In or Firebase:', error);
    }
  };


  useEffect(() => {
    // Configure Google Sign-In
    GoogleSignin.configure({
      scopes: ['https://www.googleapis.com/auth/userinfo.email'],
      iosClientId: '1:116553308885:ios:3c93a4a78b49b868a3e05c',
      webClientId: '116553308885-mvqbb5ku69pgggjl69ul2i75uhffq4b8.apps.googleusercontent.com',
    });
  }, []);
  
  const handleGoogleSignIn = async () => {
    try {
      await GoogleSignin.signOut(); // Add this line to sign the user out from Google first
      await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
      const { idToken } = await GoogleSignin.signIn();

  
      console.log('Google ID Token obtained:', idToken);
  
      const firebaseAuth = getAuth();
      const googleCredential = GoogleAuthProvider.credential(idToken);
  
      const firebaseUserCredential = await signInWithCredential(firebaseAuth, googleCredential);
      const firebaseUser = firebaseUserCredential.user;
  
      console.log('Firebase user signed in with Google:', firebaseUser);
  
      // Log the providerData array to inspect if the email is there
      console.log('Provider Data:', firebaseUser.providerData);
  
      // Extract the provider ID
      const providerId = firebaseUser.providerData.find((data) => data.providerId === 'google.com')?.providerId || 'google.com';
  
      // If firebaseUser.email is undefined, try to get the email from providerData
      const emailFromProviderData = firebaseUser.providerData
        .filter((pd) => pd.providerId === 'google.com' && pd.email)
        .map((pd) => pd.email)[0];
  
      // Use email from providerData if available
      const emailToUse = firebaseUser.email || emailFromProviderData;
  
      // Call postSignIn with the defined email, uid and providerId.
      await postSignIn({
        email: emailToUse, // Use the potentially fallback email
        firebaseuid: firebaseUser.uid,
        provider: providerId,
      });
    } catch (error) {
      console.error('Google Sign-In error:', error);
      return null;
    }
  };

  async function postSignIn({ email, firebaseuid, provider }) {
    // Your logic to handle the sign in after firebase authentication
    console.log('Post sign-in data:', { email, firebaseuid, provider });

    const payload = {
      email: email,
      firebaseuid: firebaseuid,
      provider: provider,
    };

    console.log(payload);
  
    try {
      // Start the fetch call
      const response = await fetch('https://api.xazahealth.com/loginAlt', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });
  
      // Parse the JSON response
      const data = await response.json();
      console.log(data);
  
      if (data.success) {
        if (data.message === 'Login Successful! Navigating to initial account configuration.') {
          console.log("Initial account configuration needed")
          // Navigate to the InitialAccountConfigurationScreen
          navigation.navigate('InitialAccountConfiguration', {
            email: email,
            firebaseuid: firebaseuid,
            provider: provider,
          });
        } else {
          try {
            // Save data to AsyncStorage and navigate
            await AsyncStorage.setItem('sessionUserProvider', data.providerid);
            await AsyncStorage.setItem('sessionUserEmail', data.email);
            await AsyncStorage.setItem('sessionUserUsername', data.username);
            await AsyncStorage.setItem('sessionUserFirstName', data.firstname || '');  // use empty string if null
            await AsyncStorage.setItem('sessionUserLastName', data.lastname || '');  // use empty string if null
            await EncryptedStorage.setItem('sessionUserFirebaseUID', data.firebaseuid);
    
            // Navigate to the Home screen
            navigation.reset({
              index: 0,
              routes: [{ name: 'Home' }],
            });
          } catch (error) {
            // Handle errors saving data
            console.log('Error saving user data:', error);
            setGeneralMessageModalData({
              success: false,
              visible: true,
              title: 'Error',
              message: data.message || 'Login failed.'
            });
          }
        }
      } else {
        // Handle login failed
        setGeneralMessageModalData({
          success: false,
          visible: true,
          title: 'Error',
          message: data.message || 'Login failed.'
        });
        setGeneralMessageModalVisible(true);
      }
    } catch (error) {
      // Handle API call error
      console.log('API call error:', error);
      setGeneralMessageModalData({
        success: false,
        visible: true,
        title: 'Service Unavailable',
        message: 'We apologize for the inconvenience! XAZA Health is offline at this time. Please try again later.'
      });
      setGeneralMessageModalVisible(true);
    }
  };


  const handleLogin = () => {
    navigation.navigate('Login');
  };

  const handleSignup = () => {
    navigation.navigate('Signup');
  };

  const animation = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.loop(
        Animated.sequence([
            Animated.timing(animation, {
                toValue: 1,
                duration: 5000,  // Increasing the duration for a smoother animation
                useNativeDriver: true,
            }),
            Animated.delay(300)  
        ])
    ).start();
  }, []);

 
  const d = animation.interpolate({
    inputRange: [
        0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375,
        0.5, 0.5625, 0.625, 0.6875, 0.75, 0.8125, 1
    ],
    outputRange: [
        'M0,50 L40,50 L60,50 L80,50 L100,50 L120,50 L140,50 L160,50 L200,50',    // flat line
        'M0,50 L40,50 L60,45 L80,50 L100,50 L120,50 L140,50 L160,50 L200,50',    // slight rise
        'M0,50 L40,50 L60,40 L80,50 L100,50 L120,50 L140,50 L160,50 L200,50',    // P wave
        'M0,50 L40,50 L60,50 L80,53 L100,35 L120,55 L140,50 L160,50 L200,50',    // Q wave
        'M0,50 L40,50 L60,50 L80,60 L100,25 L120,60 L140,50 L160,50 L200,50',    // R wave
        'M0,50 L40,50 L60,50 L80,53 L100,45 L120,53 L140,50 L160,50 L200,50',    // S wave
        'M0,50 L40,50 L60,50 L80,55 L100,50 L120,55 L140,55 L160,50 L200,50',    // T wave
        'M0,50 L40,50 L60,50 L80,50 L100,50 L120,50 L140,50 L160,52 L200,50',    // flat line
        'M0,50 L40,50 L60,55 L80,50 L100,50 L120,50 L140,50 L160,50 L200,50',    // slight dip
        'M0,50 L40,50 L60,60 L80,50 L100,50 L120,50 L140,50 L160,50 L200,50',    // inverse P wave
        'M0,50 L40,50 L60,50 L80,47 L100,65 L120,45 L140,50 L160,50 L200,50',    // inverse Q wave
        'M0,50 L40,50 L60,50 L80,40 L100,75 L120,40 L140,50 L160,50 L200,50',    // inverse R wave
        'M0,50 L40,50 L60,50 L80,47 L100,55 L120,47 L140,50 L160,50 L200,50',    // inverse S wave
        'M0,50 L40,50 L60,50 L80,45 L100,50 L120,45 L140,45 L160,50 L200,50',    // inverse T wave
        'M0,50 L40,50 L60,50 L80,50 L100,50 L120,50 L140,50 L160,50 L200,50',     // back to flat line
    ],
  });

  /*

  useEffect(() => {
    const unsubscribe = auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('User is signed in:', user);
      } else {
        console.log('User is signed out');
      }
    });
  
    return () => unsubscribe();  // Unsubscribe on component unmount
  }, []);


  */

  BlankHeader(navigation);

  return (
    <View style={stylesSplashScreen.container}>
      <View style={stylesSplashScreen.centeredContent}>
        <Text style={stylesSplashScreen.text}>
          XAZA Health
        </Text>
      </View>

      <Svg style={{ marginTop: -70 }} width="100%" height="100" viewBox="0 0 200 100">
        <AnimatedPath
          d={d}
          fill="none"
          stroke="#F9C400"
          strokeWidth="2"
        />
      </Svg>



      <View style={{ flex: 2, justifyContent: 'center' }}>
        {Platform.OS === 'android' && (
          <>
            <GoogleSignInButton onGoogleButtonPress={handleGoogleSignIn} />
            <CustomButtonEnabled 
              title="Create Account" 
              onPress={handleSignup}
            />
            <CustomButtonEnabled 
              title="Login" 
              onPress={handleLogin}
            />
          </>
        )}

        {Platform.OS === 'ios' && (
          <>
            <AppleSignInButton onAppleButtonPress={handleAppleSignIn} />
            <CustomButtonEnabled 
              title="Create Account" 
              onPress={handleSignup}
            />
            <CustomButtonEnabled 
              title="Login" 
              onPress={handleLogin}
            />
          </>
        )}
      </View>

      <View style={styles.footer}>
        <Text style={styles.footerText}>
          Signing in to this app implies continued acceptance of our{" "}
          <Text 
            style={styles.hyperlink} 
            onPress={() => navigation.navigate('TermsAndConditions')}
          >
            Terms and Conditions
          </Text>
          {" "}and{" "}
          <Text 
            style={styles.hyperlink} 
            onPress={() => navigation.navigate('PrivacyPolicy')}
          >
            Privacy Policy
          </Text>.
        </Text>
      </View>


      <GeneralMessageModal 
        generalMessageModalVisible={generalMessageModalVisible}
        generalMessageModalData={generalMessageModalData}
        handlePressingOK={() => setGeneralMessageModalVisible(false)}
      />

      <GeneralMessageNoButtonsModal 
        modalData={{
          visible: shouldUpdateApp,
          title: 'Update Required',
          message: 'You need to update the app to the latest version to continue.',
        }}
      />
      <GeneralMessageNoButtonsModal 
        modalData={{
          visible: !!errorMessage,
          title: 'Error',
          message: errorMessage,
        }}
      />
    </View>
  );
};


const styles = StyleSheet.create({
  // ...other styles,
  signInImage: {
    width: 200,
    height: 200,
    resizeMode: 'contain', // This ensures the aspect ratio is maintained
  },
  
  footer: {
    padding: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  footerText: {
    fontSize: 10,
    color: '#F5F5F5', // Adjust the color as needed
    textAlign: 'center',
  },
  hyperlink: {
    color: '#0CCAFF', // Hyperlink color
    textDecorationLine: 'underline',
  },
  
});

export default SplashScreen;

I have tried quite a bit of things (different devices, file modifcations, etc) Been working and sending this into GPT4 full files over the last few days and this thing is pretty much telling me to just ask the community, it is ‘puzzled’ as am I.

EDIT 1: Can’t include HomeScreen.js i’ve exceeded stacks limits. Also can’t include logs i’m seeing :/

Problem while comparing two .toString() arrays JS [duplicate]

I have following code for comparing winning patterns that are stored in array and player position.

function checkForWin(winPattern,playerPositions) {
    winPattern.forEach(element => {
        console.log(element.toString(","));
        console.log(playerPositions.toString(","));
        if(element.toString("")==playerPositions.toString("")){
            return true;
        }
    });
    return false;
}

I don’t know why it doesn’t return true if there is exact same string.

console.log(checkForWin([ [0,3,6] ],[0,3,6]))

Does anyone know what’s causing this ?

I’ve tried several solutions, but none of them really worked out.