getsession returns null doing github Oauth

// layout.js file

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import SessionWrapper from "../components/Session-Wrapper";
import  Navbar from "../components/Navbar";
import { getSession } from "next-auth/react"; 

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};
  
export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getSession(); 
  console.log("session is: " + session);
  

  return (
    <html lang="en">
      <body className={inter.className}>
        <SessionWrapper session={session}>
          <div className="overflow-hidden">
            <div className="h-[10vh]">
              <Navbar />
            </div>
            <div className="flex flex-col max-h-min bg-slate-950">
              {children}
            </div>
          </div>
        </SessionWrapper>
      </body>
    </html>
  );
}

// session-wrapper.tsx file

"use client"
import React from 'react';
import { SessionProvider } from "next-auth/react";

type SessionWrapperProps = {
  children: React.ReactNode;
  session: any;
};

const SessionWrapper: React.FC<SessionWrapperProps> = ({ children, session }) => {
  return (
    <SessionProvider session={session}>
      {children}
    </SessionProvider>
  );
};

export default SessionWrapper;

response image

why getsession is returning null here, can anyone tell me this error. I am using Github Oauth but session is comming null I am not using any form just using github Oauth and google Oauth.
github repo:- https://github.com/TanmayChaurasia24/FundMe

how do we add a button that shows in google meet page on the left side of audio if our extension is installed?

I am developing a Chrome extension that adds a button to the left side of the audio control in Google Meet. The button should only be visible if our extension is installed. I have tried adding the button using the following code, but the button is not visible.

<button id="my-button" class="gm-button gm-button-flat gm-button-secondary gm-button-size-medium">
  My Button
</button>
#my-button {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1000;
}
document.addEventListener('DOMContentLoaded', () => {
  const button = document.createElement('button');
  button.id = 'my-button';
  button.classList.add('gm-button', 'gm-button-flat', 'gm-button-secondary', 'gm-button-size-medium');
  button.textContent = 'My Button';
  const audioControl = document.querySelector('.gm-video-control');
  audioControl.insertBefore(button, audioControl.firstChild);
});

Javascript window.open does not open to the size I pass in

We have a security screen that opens a popup dialog box using a new custom script showWin that I wrote.

The security screen:

Private Sub SecCheck()
    Dim sScreenName As String = String.Format("{0}", Request("SCREEN"))
    Dim memb As MembershipUser = Membership.GetUser(User.Identity.Name)

    If Roles.IsUserInRole(memb.UserName, sScreenName) Then
        Dim params As String = String.Format("{0}", Request("PARAMS"))
        If Not String.IsNullOrWhiteSpace(params) Then
            params = String.Format("?{0}", Request("PARAMS").Replace("$", "&"))
        End If
        Dim size As Size = ClaimsInfo.SecurityDB.GetScreenSize(sScreenName)
        ' Derive Java String
        Dim target As String = String.Format("frm{0}.aspx", sScreenName)
        Dim link As String = String.Format("{0}{1}", target, params)
        Dim height As String = CStr(size.Height)
        Dim width As String = CStr(size.Width)
        Dim parent As String = "self" ' Session("IFrame")
        If (String.IsNullOrEmpty(parent)) Then
            parent = "_blank"
        End If
        Dim js As String = String.Format("showWin('{0}', {1}, {2}, 1, '{3}', '{4}');self.close();", link, width, height, target, parent)
        imgSec1.Attributes.Add("onLoad", js)
    End If
End Sub

I have placed a breakpoint where js is defined above, and I can see that the text being sent is:

showWin('frmHEIPayment.aspx', 886, 505, 1, 'frmHEIPayment.aspx', 'self');self.close();

Every time I call it, the dialog opens full screen. I’ve even edited the JavaScript command line above to use the sizes 200 and 200, but the dialog still opens the full size.

The JavaScript for showWin is below:

function showWin(link, width, height, type, target, sParent) {
    width = width || 400;
    height = height || 200;
    var features =
        'width:' + width + 'px,' +
        'height:' + height + 'px,' +
        'toolbar=no,' +
        'location=no,' +
        'menubar=no,' +
        'resizable=yes,' +
        'scrollbars=yes';
    target = target || "_blank";
    var childWindow = window.open(link, target, features);
    switch (type) {
        case 0:
            return false;
            break;
        case 1:
            __doPostBack();
            sParent = sParent || "self";
            childWindow.opener.location = sParent;
            break;
        case 2:
            CloseDialogSessionExpired(window, 2)
            return false;
            break;
        default:
            return false;
            break;
    }
}

Also, showWin does not close the security screen with self.close() like what happens whenever I use our older jsOW (JavaScript Open Window) code.

I need to replace our older jsOW JavaScript that uses IE’s window.showModalDialog:

function jsOW(link, width, height, type, sName) {
    var sFeature = "status:no;dialogWidth:" + width + "px;dialogHeight:" + height + "px;dialogHide:true;help:no;scroll:no";
    if (type == "1") {
        var vVar = window.showModalDialog(link, window, sFeature);
        if (typeof (vVar) == 'boolean') {
            return vVar;
        } else {
            switch (vVar) {
                case 0:
                    return false;
                    break;
                case 1:
                    __doPostBack();
                    break;
                case 2:
                    CloseDialogSessionExpired(window, 2)
                    return false;
                    break;
                default:
                    return false;
                    break;
            }
        }
    }
}

It displays the form with the correct size, but it only works in IE or Edge in Compatibility Mode.

How do I get this JavaScript to work?

Next JS with Okta/ Auth0 logout redirect works on desktop but not on mobile

Logging out users using auth0 logout action works fine on desktop but does not work on mobile (iphone, safari). I see a quick page refresh but the user remains logged in. How can this be debbuged?

The flow is as follows:

1. Client side trigger

const handleLogoutUser = async () => {
    logOutUser()
  }

2. Hitting the Auth0 logout URI

export const logOutUser = (tokenExpired: boolean = false, authError: boolean = false) => {
  const returnToBase = window.location.origin // Your app's base URL
  const customParam = 'loggedOut=true' // Custom parameter

  // Conditionally add the tokenExpired or other custom parameters
  const params = [customParam]
  if (tokenExpired) {
    params.push('tokenExpired=true')
  }
  if (authError) {
    params.push('authError=true')
  }

  const returnTo = encodeURIComponent(`${returnToBase}?${params.join('&')}`)

  window.location.href = `${AUTH_ZERO_DOMAIN}/v2/logout?client_id=${AUTH_ZERO_CLIENT_ID}&returnTo=${returnTo}&forceLogout=true`

  return true
}

3. Upon redirect, useEffect is trigged to help clear the rest of the session in the BE, FE and resetting state.

  useEffect(() => {
    if (query?.loggedOut === 'true' && isLoggedIn) {
      handleClearSession()
    }

    if (query?.tokenExpired === 'true') {
      handleClearSession()
    }

    if (query?.authError === 'true') {
      handleClearSession()
    }
  }, [query, isLoggedIn])

4. Finishing the logout

  const handleClearSession = async () => {
    setAuthZeroAccessToken(null)
    setIsLoggedIn(false)
    localStorage.removeItem(AUTH_ZERO_TOKEN_LOCAL_STORAGE_KEY)

    // Remove 'loggedOut' from the URL
    const updatedQuery = { ...query }
    // Delete queries
    delete updatedQuery.loggedOut
    delete updatedQuery.tokenExpired
    delete updatedQuery.authError

    const clearSession = await clearSessionMultipleRuns()
    if (clearSession) {
      await mutate('/action/account/getAccount', {})
      await mutate('/action/cart/getCart', {})
      handleShallowRouteReplace(router, updatedQuery)
    }
  }

Overlaying div over textarea for text highlighting – alignment breaks when scrolled all the way to the right

I want to be able to highlight matches in user editable text, so I decided to do the standard exercise of creating a <div> that floats above the textarea and highlight the text in that div.

I got it almost perfect in about 30 minutes, so I am almost happy. The problem is, when you scroll all the way to right/bottom, the alignment breaks.

Try it, it’s quite neat except for that little bug. Once you scroll the textarea all the way down, the alignment between the text in the textarea and my overlay div breaks.

class TextareaOverlay {
    /**
     * 
     * @param {HTMLDivElement} container 
     */
    constructor(container) {
        /** @type {HTMLTextAreaElement} */
        this.textarea = container.querySelector("textarea");
        /** @type {HTMLDivElement} **/
        this.overlay = document.createElement("div");
        this.overlay.classList.add("overlay");
        container.appendChild(this.overlay);

        this.textarea.addEventListener("input", this.inputHandler.bind(this));
        this.textarea.addEventListener("scroll", this.scrollHandler.bind(this));
        this.inputHandler();
        this.sizeHandler();
        this.scrollHandler();
        this.resizeObserver = new ResizeObserver(this.sizeHandler.bind(this));
        this.resizeObserver.observe(this.textarea);
    }
    inputHandler() {
        const text = this.textarea.value;
        this.overlay.textContent = text;
    }
    scrollHandler() {
        this.overlay.scrollTop = this.textarea.scrollTop;
        this.overlay.scrollLeft = this.textarea.scrollLeft;
    }
    sizeHandler() {
        const rect = this.textarea.getBoundingClientRect();
        this.overlay.style.width = rect.width+"px";
        this.overlay.style.height = rect.height+"px";
    }
};
const textareaHelper = new TextareaOverlay(document.querySelector(".textarea-overlay"));
div.textarea-overlay {
    position: relative;
}
div.textarea-overlay textarea {
    width: 100%;
    height: 100%;
    padding: 10px;
    font-family: 'Courier New', Courier, monospace;
    background-color: #f8f9fa;
    margin: 0;
    box-sizing: border-box;
    overflow: scroll;
    white-space: pre;
    font-size: 1em;
}
div.textarea-overlay div.overlay {
    margin: 0;
    position: absolute;
    font-size: 1em;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 10px;
    white-space: pre;
    font-family: 'Courier New', Courier, monospace;
    pointer-events: none;
    overflow: hidden;
    box-sizing: border-box;
    border: 1px solid transparent;
}
<div class="textarea-overlay" style="width: 400px; height: 500px">
<textarea>
div.textarea-overlay {
    position: relative;
}
div.textarea-overlay textarea {
    width: 100%;
    height: 100%;
    padding: 10px;
    font-family: 'Courier New', Courier, monospace;
    background-color: #f8f9fa;
    margin: 0;
    box-sizing: border-box;
    overflow: scroll;
    white-space: pre;
    font-size: 1em;
}
div.textarea-overlay div.overlay {
    margin: 0;
    position: absolute;
    font-size: 1em;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 10px;
    white-space: pre;
    font-family: 'Courier New', Courier, monospace;
    pointer-events: none;
    overflow: hidden;
    box-sizing: border-box;
    border: 1px solid transparent;
}
</textarea>
</div>

So the question is how to deal with the scrolling issue. Bonus points if you also know how would I go about displaying text cursor in the overlay in case I wanted to hide the original text completely.

React native Routing/Navigation between screens not working

I am unable to get my react native naviagtion screen working. I am trying to access two screens, one CancerHomepageWeb and the other ChemoHomepageWeb. I would like to put the screen name is the routing URL to access each screen. Here is my code:

index.js

import {NavigationContainer} from '@react-navigation/native';
import { useNavigation } from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import { useIsFocused } from "@react-navigation/native";
import { CancerHomepageWeb } from './CancerHomepageWeb.js';
import { ChemoHomepageWeb } from './ChemoHomepageWeb.js';
import { MainSideBarWeb } from './MainSideBarWeb.js';
import React from 'react';
import {Text, View} from 'react-native';
import { registerRootComponent } from 'expo';

const Stack = createNativeStackNavigator();

const App = () => {
    return (
    <NavigationContainer>
        <Stack.Navigator initialRouteName="CancerHomepageWeb">
            <Stack.Screen
                name="CancerHomepageWeb"
                component={CancerHomepageWeb}
            />
            <Stack.Screen
                name="ChemoHomepageWeb"
                component={ChemoHomepageWeb}
            />
        </Stack.Navigator>
    </NavigationContainer>
    );
};
export default registerRootComponent(App);

CancerHomepageWeb.js

import { StatusBar } from "expo-status-bar";
import React, { useState, Component, useEffect } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  Button,
  Alert,
  TouchableOpacity,
  Modal,
  Pressable
} from "react-native";
import { useIsFocused } from "@react-navigation/native";
import { registerRootComponent } from 'expo';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import { useNavigation } from '@react-navigation/native';
import constants from './Constants.js';
import { styles } from './CommonStylesWeb.js';
import RNPickerSelect from 'react-native-picker-select';
import { MainSideBarWeb } from './MainSideBarWeb'

const CancerHomepageWeb = ({navigation}) => {
    const [cancerWiki, setCancerWiki] = useState("");
    const [cancerType, setCancerType] = useState("");
    const [selectedValue, setSelectedValue] = useState(null);
    const [selectedLabel, setSelectedLabel] = useState(null);
    const [options, setOptions] = useState([]);
    const [cancerWikiContent, setCancerWikiContent] = useState("");
    //const navigation = useNavigation();
    console.log("navigation ", navigation);
    useEffect(() => {
        const getData = async () => {

            var urlCancerWiki = await constants.getServerURL() + 'cancers_wiki';
            console.warn(urlCancerWiki);
            let resultCancerWiki = await fetch(urlCancerWiki, {
                method: "GET", mode: 'cors'
                }).then(response => response.json())
                    .then(response => {
                        if (response) {
                            console.warn(response)
                            setCancerWiki(response)
                        }
                });
        };
        getData();
    }, []);
    async function handleChangeCancer(value, index) {
      console.warn("CANCER HAS CHANGED");
      setSelectedValue(value);
      console.warn(value)
      if(index > 0) {
          indexOffset = index - 1;
          console.warn(options[indexOffset].label);
          setSelectedLabel(options[indexOffset].label);

          const url = await constants.getServerURL() + 'cancer_wiki';
          console.warn(url);
          let result = fetch(url, {
             method: 'POST',
             headers: { 'Content-Type': 'application/json' },
             body: JSON.stringify({ id: value}),
             mode: 'cors'
           }).then(response => response.json())
             .then(response => {
                if (response) {
                    setCancerWikiContent(response)
                    setCancerWiki("")
                }
           });

      }
    };
    const searchCancers = async() => {
        const url = await constants.getServerURL() + 'cancer_name';
        console.warn(url);
        console.warn(cancerType);
        if (cancerType.length >= 3) {
            let result = fetch(url, {
               method: 'POST',
               headers: { 'Content-Type': 'application/json' },
               body: JSON.stringify({ cancer_type: cancerType}),
               mode: 'cors'
             }).then(response => response.json())
               .then(response => {
               setOptions([]);
               optionsTemp = [];
               console.warn("GETTING CANCER RESPONSE")
               console.warn(response)
               if (response) {
                    //setCancer = response.cancers
                    console.warn("VALID CANCER RESPONSE")
                    response.map( (cancer) => {
                        optionsTemp.push(new Object({label:cancer.name , value: cancer.id}));
                    });
                    console.warn(optionsTemp)
                    setOptions(optionsTemp);
               } else {
                   console.warn("Error retrieving Cancer");
                   //setErrorMessage("Error Getting Cancers!");
                   //setErrorVisible(true);
               }
              });
        }
    }
    return (

    <View style={styles.sideBar}>
        <StatusBar style="auto" />
        <View style={styles.container}>
            <TextInput
              style={styles.TextInput}
              placeholder="Cancers"
              placeholderTextColor="#003f5c"
              onChangeText={(cancerType) => setCancerType(cancerType)}
              onKeyPress={searchCancers}
            />
        </View>
        <View style={styles.container}>
            <Text>Select Cancer</Text>
            <RNPickerSelect
              items={options}
              onValueChange={(value, index)  =>
                handleChangeCancer(value,index)}
              value={selectedValue}
            />
            {selectedValue && <Text>Selected: {selectedLabel}</Text>}
        </View>
        <ScrollView>
             <View style={styles.inputView}>
                 <Text>{cancerWikiContent}</Text>
                 <Text>{cancerWiki}</Text>
             </View>
        </ScrollView>
    </View>
);
}



export { CancerHomepageWeb };

ChemoHomepageWeb.js

import { StatusBar } from "expo-status-bar";
import React, { useState, Component, useEffect } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  Button,
  Alert,
  TouchableOpacity,
  Modal,
  Pressable
} from "react-native";
import { useIsFocused } from "@react-navigation/native";
import { registerRootComponent } from 'expo';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import { useNavigation } from '@react-navigation/native';
import constants from './Constants.js';
import { styles } from './CommonStylesWeb.js';
import RNPickerSelect from 'react-native-picker-select';
import { MainSideBarWeb } from './MainSideBarWeb'

const ChemoHomepageWeb = ({navigation}) => {
    const [chemoWiki, setChemoWiki] = useState("");
    const [chemoType, setChemoType] = useState("");
    const [selectedValue, setSelectedValue] = useState(null);
    const [selectedLabel, setSelectedLabel] = useState(null);
    const [options, setOptions] = useState([]);
    const [chemoWikiContent, setChemoWikiContent] = useState("");
    //const navigation = useNavigation();
    console.log("navigation ", navigation);
    useEffect(() => {
        const getData = async () => {

            var urlChemoWiki = await constants.getServerURL() + 'chemos_wiki';
            console.warn(urlChemoWiki);
            let resultChemoWiki = await fetch(urlChemoWiki, {
                method: "GET", mode: 'cors'
                }).then(response => response.json())
                    .then(response => {
                        if (response) {
                            console.warn(response)
                            setChemoWiki(response)
                        }
                });
        };
        getData();
    }, []);
    async function handleChangeChemo(value, index) {
      console.warn("CHEMO HAS CHANGED");
      setSelectedValue(value);
      console.warn(value)
      if(index > 0) {
          indexOffset = index - 1;
          console.warn(options[indexOffset].label);
          setSelectedLabel(options[indexOffset].label);

          const url = await constants.getServerURL() + 'chemo_wiki';
          console.warn(url);
          let result = fetch(url, {
             method: 'POST',
             headers: { 'Content-Type': 'application/json' },
             body: JSON.stringify({ id: value}),
             mode: 'cors'
           }).then(response => response.json())
             .then(response => {
                if (response) {
                    setChemoWikiContent(response)
                    setChemoWiki("")
                }
           });

      }
    };
    const searchChemos = async() => {
        const url = await constants.getServerURL() + 'chemo_name';
        console.warn(url);
        console.warn(chemoType);
        if (chemoType.length >= 3) {
            let result = fetch(url, {
               method: 'POST',
               headers: { 'Content-Type': 'application/json' },
               body: JSON.stringify({ chemo_type: chemoType}),
               mode: 'cors'
             }).then(response => response.json())
               .then(response => {
               setOptions([]);
               optionsTemp = [];
               console.warn("GETTING CHEMO RESPONSE")
               console.warn(response)
               if (response) {
                    console.warn("VALID CHEMO RESPONSE")
                    response.map( (chemo) => {
                        optionsTemp.push(new Object({label:chemo.name , value: chemo.id}));
                    });
                    console.warn(optionsTemp)
                    setOptions(optionsTemp);
               } else {
                   console.warn("Error retrieving Chemo drug");
                   //setErrorMessage("Error Getting Chemo drugss!");
                   //setErrorVisible(true);
               }
              });
        }
    }
    return (
    <View style={styles.container}>
        <StatusBar style="auto" />
        <View style={styles.inputView}>
            <TextInput
              style={styles.TextInput}
              placeholder="CHemo"
              placeholderTextColor="#003f5c"
              onChangeText={(chemoType) => setChemoType(chemoType)}
              onKeyPress={searchChemos}
            />
        </View>
        <View style={styles.inputView}>
            <Text>Select Chemo Drug</Text>
            <RNPickerSelect
              items={options}
              onValueChange={(value, index)  =>
                handleChangeChemo(value,index)}
              value={selectedValue}
            />
            {selectedValue && <Text>Selected: {selectedLabel}</Text>}
        </View>
        <ScrollView>
             <View style={styles.inputView}>
                 <Text>{chemoWikiContent}</Text>
                 <Text>{chemoWiki}</Text>
             </View>
        </ScrollView>
    </View>
);
}



export { ChemoHomepageWeb };

Here is my package.json

{
  "name": "cancerhacked",
  "main": "expo-router/entry",
  "version": "1.0.0",
  "scripts": {
    "start": "expo start",
    "reset-project": "node ./scripts/reset-project.js",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "test": "jest --watchAll",
    "lint": "expo lint"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/vector-icons": "^14.0.2",
    "@react-native-picker/picker": "^2.9.0",
    "@react-navigation/native": "^6.0.2",
    "expo": "~51.0.28",
    "expo-constants": "~16.0.2",
    "expo-font": "~12.0.9",
    "expo-linking": "~6.3.1",
    "expo-router": "~3.5.23",
    "expo-splash-screen": "~0.27.5",
    "expo-status-bar": "~1.12.1",
    "expo-system-ui": "~3.0.7",
    "expo-web-browser": "~13.0.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.74.5",
    "react-native-gesture-handler": "~2.16.1",
    "react-native-network-info": "^5.2.1",
    "react-native-picker-select": "^9.3.1",
    "react-native-public-ip": "^1.0.2",
    "react-native-reanimated": "~3.10.1",
    "react-native-safe-area-context": "4.10.5",
    "react-native-screens": "3.31.1",
    "react-native-web": "~0.19.10"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@types/jest": "^29.5.12",
    "@types/react": "~18.2.45",
    "@types/react-test-renderer": "^18.0.7",
    "jest": "^29.2.1",
    "jest-expo": "~51.0.3",
    "react-test-renderer": "18.2.0",
    "typescript": "~5.3.3"
  },
  "private": true
}

Whatever route I put in my localhost I always get the Cancer App. If I put a navigation call to the Chemo screen navigation.navigate("ChemoHomepageWeb") it still goes to the Cancer page not the Chemo. Any help is welcome.

Is there ANY faster way to parse results than mysqli_fetch_assoc()?

Okay, here’s the deal. I’m working on pulling historical data from a table to be charted for the user. The front end is HTML/JS, the back end is PHP.

So our table has over 90 columns in it. It’s all the data from a DC generator (or two) during operation, updated every minute. Includes high, low, and last results for that minute, so it’s 3-6 rows per minute.

Right now, if I want to pull data for gen 0 from the last week, I use a query like this:

SELECT voltage,current,timestamp,type FROM genset WHERE genID = 0 AND timestamp > '2024/11/20 11:43:00' AND timestamp < '2024/11/27 11:43:00' ORDER BY timestamp ASC;

Now, the query takes seconds, despite the fact the database is on an SD card on a single-board computer attached to a generator somewhere. But parsing the data in PHP… if I grab a month of data for 1 generator, you’re looking at 130,000 rows or so. And for every single row, I then iterate a loop like this to parse and format it:

while($row=mysqli_fetch_assoc($raw)) {
    //parse and format the data
    //...
}

Then $reply goes back to the JS front end (this was all in a HTTP POST sent to a back-end PHP script), where it’s run through a chart library to be displayed to the user.

So my boss wants this to run WAY faster. One thing I did to help with the perceived speed was to break up the query into several smaller chunks and display a progress bar. This removes the sense of it “hanging” and also eliminates issues with php’s max execution time (which I can’t seem to change no matter what I do). But for a unit that’s on top of a mountain somewhere, it means every POST adds more lag time to the user’s request.

I thought mysqli_fetch_all() might solve the problem. But it turns out, that just does the same thing as the while loop! So it takes just as long.

Of course I looked at just returning $raw to JS, but I don’t know if JS is able to parse that at all. If it is, that would be great. I could get all the data – hell, all the data for all 90+ columns – and let the client parse it how they like.

Any advice, guys? Is there a way for JS to parse raw mysqli data? Is there a faster way to convert that data into an associative array?

Cache Busting in Flutter Web for New Releases: Issues with Clearing Old Cache

I’m developing a Flutter Web project, and I’m encountering issues with cache busting after deploying new releases. Despite trying multiple solutions, older versions of files (e.g., main.dart.js) seem to persist, causing users to load outdated files instead of the latest release. is there a specific way it should be done with flutter web?

Steps I’ve Tried:
File Versioning:
I appended version numbers to the names of files, such as:

.

However, this didn’t seem to resolve the issue for all users.

Service Worker Cache Management:
I added a version to the cache name variable in the service worker and updated it during releases to delete the old cache.
Unfortunately, this approach didn’t consistently work either.

html code

<!DOCTYPE html>
<html>
  <head>
    <base href="$FLUTTER_BASE_HREF">

    <meta charset="UTF-8">
    <meta content="IE=Edge" http-equiv="X-UA-Compatible">
    <meta name="description" content="A new Flutter project.">
    <link rel="icon" type="image/png" href="favicon.png">
    <link rel="manifest" href="manifest.json">

    <title>My Flutter Web App</title>

    <script>
      const serviceWorkerVersion = null;
    </script>
    <script src="flutter.js" defer></script>
    <script src="main.dart.js?v=1.0.57.39d6d65"></script>
  </head>
  <body>
    <script>
      window.addEventListener('load', function (ev) {
        _flutter.loader.loadEntrypoint({
          serviceWorker: {
            serviceWorkerVersion: serviceWorkerVersion,
          },
          onEntrypointLoaded: function (engineInitializer) {
            engineInitializer.initializeEngine().then(function (appRunner) {
              appRunner.runApp();
            });
          }
        });
      });
    </script>
  </body>
</html>

AWS Cognito w React.js localhost CORS error

I’ve seen similar issues when searching – but let’s assume I’m using AWS sample code to setup Cognito in React. Set callback / signout URI to http://localhost:3000 which is literally stated by AWS to be the one exception to needing https. Now I’m not at my workstation – but I’m pretty sure I’ve tried not using the port, but can’t see what I’m missing as I see no reason for the CORS issue as I’m not doing anything but testing login. There is no other setting in Cognito console for CORS I’m missing I don’t think – but my hosted UI link within Cognito works – just how this code calls it. Thanks for any guidance, I just don’t want to go into production just to test and develop. Is it my browser? I’m going to use Amplify which I’ve seen manages CORS but this one feels just weird. Thanks for any support!

enter image description here


// index.js
import { AuthProvider } from "react-oidc-context";

const cognitoAuthConfig = {
  authority: "https://cognito-idp.us-east-1.amazonaws.com/us-secretStuff(user pool)",
  client_id: "secretStuff client id",
  redirect_uri: "http://localhost:3000",
  response_type: "code",
  scope: "email openid phone",
};

const root = ReactDOM.createRoot(document.getElementById("root"));

// wrap the application with AuthProvider
root.render(
  <React.StrictMode>
    <AuthProvider {...cognitoAuthConfig}>
      <App />
    </AuthProvider>
  </React.StrictMode>
);

Edited out account stuff with secretStuff but those are verified.. but do note for authority it’s just ends with user pool ID.
Next up is app.js


// App.js

import { useAuth } from "react-oidc-context";

function App() {
  const auth = useAuth();

  const signOutRedirect = () => {
    const clientId = "secretStuff client ID";
    const logoutUri = "http://localhost:3000";
    const cognitoDomain = "https://us-east-secretStuff.auth.us-east-1.amazoncognito.com";
    window.location.href = `${cognitoDomain}/logout?client_id=${clientId}&logout_uri=${encodeURIComponent(logoutUri)}`;
  };

  if (auth.isLoading) {
    return <div>Loading...</div>;
  }

  if (auth.error) {
    return <div>Encountering error... {auth.error.message}</div>;
  }

  if (auth.isAuthenticated) {
    return (
      <div>
        <pre> Hello: {auth.user?.profile.email} </pre>
        <pre> ID Token: {auth.user?.id_token} </pre>
        <pre> Access Token: {auth.user?.access_token} </pre>
        <pre> Refresh Token: {auth.user?.refresh_token} </pre>

        <button onClick={() => auth.removeUser()}>Sign out</button>
      </div>
    );
  }

  return (
    <div>
      <button onClick={() => auth.signinRedirect()}>Sign in</button>
      <button onClick={() => signOutRedirect()}>Sign out</button>
    </div>
  );
}
  
export default App;

How to manage state in nextjs 15

How you manage the state in nextjs 15 and reactjs 19!?
I can’t use any package or it gives me an error when I try to install it.
I’ve been trying to install

  1. Redux toolkit
  2. Zustand
  3. jotai

so please help if you can solve it, this is the error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   peer react@"^18.2.0 || 19.0.0-rc-66855b96-20241106" from [email protected]
npm ERR!   node_modules/next
npm ERR!     peer next@"^10.0.0 || ^11.0.0 || ^12.0.0 || ^13.0.0 || ^14.0.0 || ^15.0.0" from [email protected]
npm ERR!     node_modules/next-intl
npm ERR!       next-intl@"^3.25.3" from the root project
npm ERR!     next@"15.0.3" from the root project
npm ERR!   peer react@"^16.8.0 || ^17.0.0 || ^18.0.0 || >=19.0.0-rc <19.0.0" from [email protected]
npm ERR!   node_modules/next-intl
npm ERR!     next-intl@"^3.25.3" from the root project
npm ERR!   4 more (react-dom, styled-jsx, use-intl, the root project)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional react@">=17.0.0" from [email protected]
npm ERR! node_modules/jotai
npm ERR!   jotai@"*" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/react
npm ERR!   peerOptional react@">=17.0.0" from [email protected]
npm ERR!   node_modules/jotai
npm ERR!     jotai@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:UsersmrsniAppDataLocalnpm-cache_logs2024-11-27T17_48_09_411Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: C:UsersmrsniAppDataLocalnpm-cache_logs2024-11-27T17_48_09_411Z-debug-0.log

Why doesn’t a complex key lookup in map work? [duplicate]

I have a map, where the key that is a combination of a string and a number – I assume it is an object then.

Why does the following code return false on the has() method, when I use the exact same keys (const key = {app:"App", code:5};)?

let errorItemPages = new Map();

function addItem() {
    const key = {app:"App", code:5};
    errorItemPages.set(key, "five");
}

function lookup() {
    const key = {app:"App", code:5};
    console.log(errorItemPages.has(key));
}

addItem();
lookup();

Selector unknown returned the root state when called. This can lead to unnecessary rerenders

I’m working on a React application using Redux and I’ve encountered a warning related to the useSelector hook. I am trying to extract data and loading state from multiple slices of the Redux store, as these two values are common across different API responses.

Error: Selector unknown returned the root state when called. This can lead to unnecessary rerenders. Selectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever anything in state changes.

const {
  measureData: { data: measureViewData, loading: measureViewLoading },
  lists: { data: listData, loading: listLoading },
} = useSelector((state) => ({
  measureViewData: state.measureViewData,
  list: state.list,
}));

// Redux Store setup (reducers for both slices)
export const store = configureStore({
  reducer: {
    measureViewData: measureViewDataReducer,
    list: listReducer,
  },
});

In my app, I’m fetching data from APIs, and each slice of the state contains both data and loading properties (indicating whether the API call is in progress). I’m using useSelector to extract these properties, but I am receiving the following warning in the console, which says my selector is returning the entire root state:

Warning: Selector unknown returned the root state when called. This can lead to unnecessary rerenders.

I want to be able to uniformly extract both the data and loading state from each slice, and avoid unnecessary rerenders. For example, the measureViewData slice has:

const initialState = {
data: [],
loading: false
}

And similarly, the list slice has:

const initialState = {
data: [],
loading: false
}

What I’ve Tried:

  1. I’ve reviewed the selector, and it looks like it should only return the measureViewData and list slices, but the warning suggests that it might be returning the entire root state.
  2. I’ve attempted restructuring the selector to explicitly extract only data and loading from each slice, but I’m still encountering the warning.
  3. I’ve confirmed that my reducers for measureViewData and list are set up properly and both contain data and loading states.

Question:

How can I refactor my useSelector hook to extract data and loading from each slice (like measureViewData, list, etc.) and avoid the warning about returning the entire state? I want to make sure I am efficiently accessing just the data and loading state for each slice of the Redux store, and prevent unnecessary rerenders.

Is there a better pattern or approach for accessing this common structure across different API slices?

How do I use an index file without breaking react-refresh?

Say I have a module foo and it’s got some stuff in it:

// foo/index.js
export { default as SomeComponent } from './SomeComponent'
export { someUtil } from './utilities'
export const SOME_CONSTANT = 42

Now I can import everything I need directly from foo without seeing implementation details about which file something is in:

// bar.js
import { SomeComponent, someUtil, SOME_CONSTANT } from 'foo'

So I got that going for me, which is nice.

But now I get eslint errors from my react-refresh/only-export-components rule warning me that “Fast refresh only works when a file only exports components”. Ok, it’s true that index.js exports both components and other stuff (functions, constants). Does this rule mean that my foo module/package basically can’t effectively use an index file — i.e., that either the components or the other stuff will have to be imported directly from wherever they are used?

// bar.js
import { SOME_CONSTANT, someUtil } from 'foo'
import SomeComponent from 'foo/SomeComponent'

Am I understanding the react-refresh rule here? If so, what’s the recommended pattern for module-level exports that doesn’t break it?

SessionID from tomcat is replaced but timeout not restarting?

I have a formcontrol for logging into my application. It works fine.

<form name="login" method ="POST" role="form" action="j_security_check">
      <div class="login">
         <label> Username</label>
         <input formControlName="username"  name="j_username" autofocus required>
      </div>

      <div class="login">
         <label> Password</label>
         <input type="password" formControlName="password"  name="j_password" required>
      </div>
     <button class="submit" type="submit"> Sing In</button>
</form>

In my application, I have a button that calls “logoutUser” which “invalidates” the session and takes me to the main page.

protected logoutUser() {
   this.http.post('/foo/logout', {}).subscribe ({
     next: () => {
        location.reload(); //reloads the page after the post call invalidates the session
     }});}

The tomcat’s xml.config has a default 30 minute timeout and I noticed that the login page’s session times out after 30 minutes and when i try to login again, i get the 408 Timeout from the j_security_check POST call.

I checked the Networking and I do see the sessionID changes everytime I login/logout. Is there a way to “keep alive” the login page past the timeout of 30 minutes? Because I need to clear the cache every time to remove the 30minute timeout.

I tried to reload the page using location.reload(true) but that doesn’t work.

Any recommendations? thanks

How to properly resolve imports with custom paths in Angular?

I’m using Angular 18 and trying to import a component(app1/reusable.component.ts) from one project into another one(app2).

And then, I want the component to import its dependencies from the project folder where it itself has been imported into (app2/node_modules) instead of the folder where it is located.

My folder structure looks something like the following:

root
├──app1
│  ├──...
│  ├──node_modules
│  ├──src
│  │  ├──...
│  │  ├──app
│  │  │  ├──...
│  │  │  ├──reusable.component.ts
│  
├──app2
│  ├──...
│  ├──node_modules
│  ├──src
│  │  ├──...
│  │  ├──app
│  │  │  ├──...
│  │  │  ├──app.component.ts

Where the relevant component files are:

// app1/src/app/reusable.component.ts

import { Component } from '@angular/core'; // this is an example of dependency that needs to be imported of app2/node_modu;es

@Component({
  selector: 'reusable-component',
  standalone: true,
  template: 'Reusable Component',
})
export class ReusableAppComponent {
  title = 'ReusableAppComponent';
}

and

// app2/src/app/app.component.ts

import { Component } from '@angular/core';
import { ReusableAppComponent } from '../../../app1/src/app/reusable.app.component'

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ReusableAppComponent],
  template: '<reusable-component></reusable-component>',
})
export class AppComponent {
  title = 'app2';
}

What I have tried so far. And steps to reproduce.

Setup: initialized app1 and app2 with ng new and removed app1/node_modules.

Then, assuming I could pull this off with paths option in tsconfig,
I’ve Modified the compilerOptions in app2/tsconfig.json by adding

    "baseUrl": "./",
    "paths": {
      "@angular/core": ["node_modules/@angular/core"],
      "tslib": ["node_modules/tslib"]
    }

As a result at runtime I see both ReusableComponent and Component from @angular/core get imported, however an error in the console appears:

ERROR RuntimeError: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://angular.dev/errors/NG0203
    at injectInjectorOnly (main.js:650:11)
    at ɵɵinject (main.js:660:59)
    at Object.factory (main.js:14888:45)
    at chunk-IMMNNYUP.js?v=a145dfc3:1965:35
    at runInInjectorProfilerContext (chunk-IMMNNYUP.js?v=a145dfc3:567:5)
    at R3Injector.hydrate (chunk-IMMNNYUP.js?v=a145dfc3:1964:11)
    at R3Injector.get (chunk-IMMNNYUP.js?v=a145dfc3:1854:23)
    at definition.getStandaloneInjector (main.js:14895:27)
    at ComponentFactory.create (chunk-IMMNNYUP.js?v=a145dfc3:9692:53)
    at _ApplicationRef.bootstrap (chunk-IMMNNYUP.js?v=a145dfc3:18388:38)