Delays in Playing Sound in Javascript, with jspsyche Plugin (jspsych-libet)

I am experiencing delays in playing a beep tone using the jspsyche plugin called jspsych-libet for my experiment. The timing of the sound is crucial, but I have observed delays of up to 400ms. These delays occur randomly and are relatively rare.

Upon examining the code, it appears to be straightforward. After a button click, there is a fixed 250ms timer set for playing the sound. However, the delay seems to exceed this value. Here is the code snippet where the beep is played:

setTimeout(function() {
    // play the tone
    if (context !== null) {
        startTime = context.currentTime;
        source.start(startTime);
    } else {
        audio.play();
    }
    // record cock hand angle of audio
    trial_data.theta_tone = clock.theta;
    trial_data.tone_ms = performance.now();
    // trigger estimation?
    ctrl_fcn('estimate');
}, trial.tone_delay_ms);

This code utilizes both the Web Audio API and HTML5 audio. I have attempted to use both methods, but the issue persists.

Here is the section where the audio is loaded:

// load audio
var context = jsPsych.pluginAPI.audioContext();
var audio;
// load audio file
jsPsych.pluginAPI.getAudioBuffer(trial.tone_file)
  .then(function (buffer) {
    if (context !== null) {
      audio = context.createBufferSource();
      audio.buffer = buffer;
      audio.connect(context.destination);
    } else {
      audio = buffer;
      audio.currentTime = 0;
    }
    // start the trial
    ctrl_fcn('start');
  })
  .catch(function (err) {
    console.error(`Failed to load audio file "${trial.tone_file}". Please check the file path. We recommend using the preload plugin to load audio files.`);
    console.error(err);
  });

I have researched and came across suggestions regarding preloading, but preloading (either with web audio api or the jspsyche) doesn’t seem to resolve the problem. I have also attempted alternative audio libraries like Howler.js, but the issue persists.

Also I’ve noticed that the occurrence rate can noticeably go higher when the RAM usage is high.

I’d appreciate it if you have any ideas that might help.

Uncaught TypeError on Firebase Storage

So I was trying to get an image from firebase storage using its file name, which is an ID of a user and display it. Here’s what came up:
Uncaught TypeError: Failed to resolve module specifier “firebase/storage”. Relative references must start with either “/”, “./”, or “../”.
I have tried to do so, but it just says 404.

import { initializeApp } from "https://www.gstatic.com/firebasejs/10.11.1/firebase-app.js";
import { getDatabase, ref, onValue } from "https://www.gstatic.com/firebasejs/10.11.1/firebase-database.js";//
import { getStorage, ref as storageRef, getDownloadURL } from "firebase/storage";

const appSettings = {
    databaseURL: "https://mobilelibattendance-default-rtdb.asia-southeast1.firebasedatabase.app/"
}
const app = initializeApp(appSettings);
const database = getDatabase(app);
const attendanceDB = ref(database, "users");
const storage = getStorage(app);//

const userIMG = document.getElementById("profile");
const IDNum = document.getElementById("IDNum");
const fullName = document.getElementById("fullName");
const fullBirthday = document.getElementById("fullBirthday");
const sex = document.getElementById("sex");
const street = document.getElementById("street");
const exp = document.getElementById("exp");
const cityProvince = document.getElementById("cityProvince");

 onValue(attendanceDB, function(snapshot) {
    let scannedID="CNPL0987654321"; // placeholders
    //CNPL0987654321  CNPL1234567890
    if (snapshot.exists()){
        let usersArray = Object.entries(snapshot.val());
        for (let i = 0;i<usersArray.length;i++) {
        let allUsers = usersArray[i]; //fetch users
        let userID = allUsers[0]; //fetch id
        let userInfo = allUsers[1]; //fetch info
        if (userID == scannedID){
            listUserInfo(scannedID, userInfo); //pass data
        }
    }
    }else {
        fullName.innerHTML="No user...";
    }

})

async function listUserInfo(userID, userInfo) { //receive data
    console.log(userInfo);
    let fullname = userInfo.firstname + " " + userInfo.lastname;
    let birthdate = userInfo.birthmonth + " " + userInfo.birthday + ", " + userInfo.birthyear;
    const filename = userID + ".jpg";
    const filePath = `users/${filename}`
    const imageRef = ref(storage, filePath);

    let userIMGLink = imageRef;
    try {
        const url = await getDownloadURL(imageRef);
        changeUserImage(url);
       }catch (error) {
        console.error("Error getting download URL:", error);
       }

    changeUserImage(userIMGLink);
    IDNum.innerHTML=userID;
    fullName.innerHTML=fullname;
    fullBirthday.innerHTML=birthdate;
    sex.innerHTML=userInfo.sex;
    street.innerHTML =userInfo.street;
    exp.innerHTML =userInfo.exp;
    cityProvince.innerHTML =userInfo.cityProvince;
}

I am using the url in my database storage to change the src of the element userIMG

function changeUserImage(userIMGLink) {
    let newIMG = userIMGLink;
    userIMG.src = newIMG;
    console.log(newIMG);
}

facing issue when customize month order in locale Ja with bsdatepicker

const customMonthOrder: number[] = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]; // March to February

// Get the default full month names
const defaultMonthNames: string[] = jaLocale.months as string[];

// Create an array of full month names in the custom order
const customMonthNames: string[] = customMonthOrder.map(index => defaultMonthNames[index]);

// Create an array of short month names in the custom order
const customMonthShortNames: string[] = customMonthNames.map(month => month.slice(0, 3)); // Take the first 3 characters as short names

// Create the custom locale object
const customLocale = {
  ...jaLocale,
  months: customMonthNames,
  monthsShort: customMonthShortNames,
};

// Define the custom locale
defineLocale('ja-custom', customLocale);

enter image description here

above image what happend
in this scenario label are change but value sequnce still as it’s if i will select month 2 and input field select 12 month so what is the solution.

expected behaviour is japan calender budget year start from march and end feb so that thing i want change custom order month

Compiler warnings in React framework

I am having plenty of compiler warnings in React framework. I have listed them below, also I have attached the package.json file:

WARNING in ./node_modules/@azure/msal-browser/dist/app/IPublicClientApplication.mjs
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrcappIPublicClientApplication.ts' file: Error: ENOENT: no such file or directory, open 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrcappIPublicClientApplication.ts'
 
WARNING in ./node_modules/@azure/msal-browser/dist/cache/BrowserCacheManager.mjs
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrccacheBrowserCacheManager.ts' file: Error: ENOENT: no such file or directory, open 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrccacheBrowserCacheManager.ts'
 
WARNING in ./node_modules/@azure/msal-browser/dist/crypto/BrowserCrypto.mjs
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrccryptoBrowserCrypto.ts' file: Error: ENOENT: no such file or directory, open 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrccryptoBrowserCrypto.ts'
 
WARNING in ./node_modules/@azure/msal-browser/dist/crypto/ModernBrowserCrypto.mjs
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:UsersXXXXDesktopexamplenode_modules@azuremsal-browsersrccryptoModernBrowserCrypto.ts' file: Error: ENOENT: no such file or directory, open 'C:UsersPChauhanIemployee_GitIemployee_UILoggingiEmployee-UInode_modules@azuremsal-browsersrccryptoModernBrowserCrypto.ts'`
{
  "name": "iemployee",
  "version": "1.2024.4-24.957",
  "private": true,
  "dependencies": {
    "@azure/msal-browser": "3.0.2",
    "@azure/msal-react": "2.0.2",
    "@emotion/react": "11.10.5",
    "@emotion/styled": "11.10.5",
    "@microsoft/applicationinsights-web": "^3.1.2",
    "@mui/icons-material": "5.10.9",
    "@mui/material": "5.10.13",
    "@mui/x-date-pickers": "5.0.16",
    "@reduxjs/toolkit": "1.9.2",
    "@testing-library/jest-dom": "5.16.5",
    "@testing-library/react": "13.4.0",
    "@testing-library/user-event": "13.5.0",
    "axios": "1.6.0",
    "crypto-js": "4.2.0",
    "date-fns": "2.30.0",
    "dayjs": "1.11.7",
    "fs": "^0.0.1-security",
    "html2canvas": "1.4.1",
    "import": "0.0.6",
    "jspdf": "2.5.1",
    "jspdf-autotable": "3.6.0",
    "loglevel": "^1.9.1",
    "mdb-ui-kit": "6.0.0",
    "moment": "2.29.4",
    "react": "18.2.0",
    "react-datepicker": "4.12.0",
    "react-dom": "18.2.0",
    "react-redux": "8.0.5",
    "react-router-dom": "6.4.3",
    "react-scripts": "5.0.1",
    "react-spinners": "0.13.7",
    "react-tilt": "^1.0.2",
    "react-toastify": "9.1.3",
    "redux": "4.2.0",
    "router-dom": "2.2.9",
    "serve": "^14.2.1",
    "web-vitals": "2.1.4",
    "week-utils": "1.1.0",
    "xlsx": "0.18.5"
  }
}

Is it possible to use HighCharts to implement some features of ReactFlow?

Recently I want to use HighCharts to do some features similar as ReactFlow.
My features:

  1. I can design the element myself.
  2. I can drag the element and zoom in/out the whole panel.

Is it possible to use HighCharts to implement them without ReactFlow?
If so, would you mind giving me some tips or information about it?

Thank you.

I’ve read the HighCharts document but can’t find any type of chart can meet my requirements.

The most smooth and pen like canvas drawing app [closed]

I’m trying to build the most smooth and pen like canvas drawing app using javascript.

I have tried many libs and codes but they’re not that smooth! Finally I have found this project written in typescript and by far it’s the best solution available and it’s really smooth.

https://github.com/dulnan/lazy-brush?tab=readme-ov-file

Now the issue:

Let’s say we have a canvas and we want to implement the above code on it.

Here is our canvas:

<canvas class="canvas" width="1560" height="933"></canvas>

The issue is the project doesn’t come with distribution file ready for production to plug it in my page and start using it. And no matter how I try I’m unable to make it work correctly.

Here is the two pieces of the lib code in src folder converted to the JS:

LazyBrush.ts converted to JS:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LazyPoint_1 = require("./LazyPoint");
var RADIUS_DEFAULT = 30;
var LazyBrush = /** @class */ (function () {
    /**
     * Constructs a new LazyBrush.
     */
    function LazyBrush(options) {
        if (options === void 0) { options = {}; }
        var initialPoint = options.initialPoint || { x: 0, y: 0 };
        this.radius = options.radius || RADIUS_DEFAULT;
        this._isEnabled = options.enabled === false ? false : true;
        this.pointer = new LazyPoint_1.LazyPoint(initialPoint.x, initialPoint.y);
        this.brush = new LazyPoint_1.LazyPoint(initialPoint.x, initialPoint.y);
        this.angle = 0;
        this.distance = 0;
        this._hasMoved = false;
    }
    /**
     * Enable lazy brush calculations.
     *
     */
    LazyBrush.prototype.enable = function () {
        this._isEnabled = true;
    };
    /**
     * Disable lazy brush calculations.
     *
     */
    LazyBrush.prototype.disable = function () {
        this._isEnabled = false;
    };
    /**
     * @returns {boolean}
     */
    LazyBrush.prototype.isEnabled = function () {
        return this._isEnabled;
    };
    /**
     * Update the radius
     *
     * @param {number} radius
     */
    LazyBrush.prototype.setRadius = function (radius) {
        this.radius = radius;
    };
    /**
     * Return the current radius
     *
     * @returns {number}
     */
    LazyBrush.prototype.getRadius = function () {
        return this.radius;
    };
    /**
     * Return the brush coordinates as a simple object
     *
     * @returns {object}
     */
    LazyBrush.prototype.getBrushCoordinates = function () {
        return this.brush.toObject();
    };
    /**
     * Return the pointer coordinates as a simple object
     *
     * @returns {object}
     */
    LazyBrush.prototype.getPointerCoordinates = function () {
        return this.pointer.toObject();
    };
    /**
     * Return the brush as a LazyPoint
     *
     * @returns {LazyPoint}
     */
    LazyBrush.prototype.getBrush = function () {
        return this.brush;
    };
    /**
     * Return the pointer as a LazyPoint
     *
     * @returns {LazyPoint}
     */
    LazyBrush.prototype.getPointer = function () {
        return this.pointer;
    };
    /**
     * Return the angle between pointer and brush
     *
     * @returns {number} Angle in radians
     */
    LazyBrush.prototype.getAngle = function () {
        return this.angle;
    };
    /**
     * Return the distance between pointer and brush
     *
     * @returns {number} Distance in pixels
     */
    LazyBrush.prototype.getDistance = function () {
        return this.distance;
    };
    /**
     * Return if the previous update has moved the brush.
     *
     * @returns {boolean} Whether the brush moved previously.
     */
    LazyBrush.prototype.brushHasMoved = function () {
        return this._hasMoved;
    };
    /**
     * Updates the pointer point and calculates the new brush point.
     */
    LazyBrush.prototype.update = function (newPointerPoint, options) {
        if (options === void 0) { options = {}; }
        this._hasMoved = false;
        if (this.pointer.equalsTo(newPointerPoint) &&
            !options.both &&
            !options.friction) {
            return false;
        }
        this.pointer.update(newPointerPoint);
        if (options.both) {
            this._hasMoved = true;
            this.brush.update(newPointerPoint);
            return true;
        }
        if (this._isEnabled) {
            this.distance = this.pointer.getDistanceTo(this.brush);
            this.angle = this.pointer.getAngleTo(this.brush);
            var isOutside = Math.round((this.distance - this.radius) * 10) / 10 > 0;
            var friction = options.friction && options.friction < 1 && options.friction > 0
                ? options.friction
                : undefined;
            if (isOutside) {
                this.brush.moveByAngle(this.angle, this.distance - this.radius, friction);
                this._hasMoved = true;
            }
        }
        else {
            this.distance = 0;
            this.angle = 0;
            this.brush.update(newPointerPoint);
            this._hasMoved = true;
        }
        return true;
    };
    return LazyBrush;
}());
exports.default = LazyBrush;

LazyPoint.ts converted to JS:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LazyPoint = void 0;
function ease(x) {
    return 1 - Math.sqrt(1 - Math.pow(x, 2));
}
var LazyPoint = /** @class */ (function () {
    function LazyPoint(x, y) {
        this.x = x;
        this.y = y;
    }
    /**
     * Update the x and y values
     */
    LazyPoint.prototype.update = function (point) {
        this.x = point.x;
        this.y = point.y;
        return this;
    };
    /**
     * Move the point to another position using an angle and distance
     */
    LazyPoint.prototype.moveByAngle = function (
    // The angle in radians
    angle, 
    // How much the point should be moved
    distance, 
    // How much of the required distance the coordinates are moved. A value of
    // 1 means the full distance is moved. A lower value reduces the distance
    // and makes the brush more sluggish.
    friction) {
        // Rotate the angle based on the browser coordinate system ([0,0] in the top left)
        var angleRotated = angle + Math.PI / 2;
        if (friction) {
            this.x = this.x + Math.sin(angleRotated) * distance * ease(1 - friction);
            this.y = this.y - Math.cos(angleRotated) * distance * ease(1 - friction);
        }
        else {
            this.x = this.x + Math.sin(angleRotated) * distance;
            this.y = this.y - Math.cos(angleRotated) * distance;
        }
        return this;
    };
    /**
     * Check if this point is the same as another point
     */
    LazyPoint.prototype.equalsTo = function (point) {
        return this.x === point.x && this.y === point.y;
    };
    /**
     * Get the difference for x and y axis to another point
     */
    LazyPoint.prototype.getDifferenceTo = function (point) {
        return new LazyPoint(this.x - point.x, this.y - point.y);
    };
    /**
     * Calculate distance to another point
     */
    LazyPoint.prototype.getDistanceTo = function (point) {
        var diff = this.getDifferenceTo(point);
        return Math.sqrt(Math.pow(diff.x, 2) + Math.pow(diff.y, 2));
    };
    /**
     * Calculate the angle to another point
     */
    LazyPoint.prototype.getAngleTo = function (point) {
        var diff = this.getDifferenceTo(point);
        return Math.atan2(diff.y, diff.x);
    };
    /**
     * Return a simple object with x and y properties
     */
    LazyPoint.prototype.toObject = function () {
        return {
            x: this.x,
            y: this.y
        };
    };
    return LazyPoint;
}());
exports.LazyPoint = LazyPoint;

Based on the reference on github we can initial the brush using :

const lazy = new LazyBrush({
  radius: 30,
  enabled: true,
  initialPoint: { x: 0, y: 0 }
})

I can’t even understand how to connect my canvas to this?

Any help will be greatly appreciated

How to run ajax without internet [closed]

I developed an invoices project using Laravel on a local server and I used AJAX to retrieve material information from the database when the user enters the material card number, but the AJAX tool only works when connected to the Internet, but my project must work in offline mode.
Any Help..


<script>
    $(document).ready(function() {
                    var id = this.id;
                    $('#card_num').on('change', function() {
                            var card_number = $(this).val();`your text`
                            if (card_number) {
                                $.ajax({
                                    url: "{{ URL::to('object') }}/" + card_number,
                                    type: "GET",
                                    dataType: "json",
                                    success: function(data) {
                                    $('#obj_name').val(data.object_name);
                                    $('#unit_name').val(data.unit_name);
                                    },
                                });
                            } else {
                                console.log('AJAX load did not work');
                            }
                            });
                        });
</script>



How to send blob via resolve() and onResult()

as shown in the below posted code, in the method attachGeoTIFFAsOverlayForPath, it invokes stream method which in turn calls fetch to communicate with the backend.
the log statements of stream method are as shown in the screen-shot attached below.

the problem is, despite the log statements of stream method indicate that there is a value assigned to the response object, however, the logs in attachGeoTIFFAsOverlayForPath method show that the blob object passed to attachGeoTIFFAsOverlayForPath method
is empty as shown in the last line of the output posted in the attached screen-shot below

why the reponse object passed back to attachGeoTIFFAsOverlayForPath method is empty despite the logs indicate that it, indeed, has value

attachGeoTIFFAsOverlayForPath:

attachGeoTIFFAsOverlayForPath(nameOfGeoTIFF) {
    if (nameOfGeoTIFF) {
        if (typeof nameOfGeoTIFF === 'string') {

            this.#wsGeoTIFFStreamer = new WSGeoTIFFStreamer(nameOfGeoTIFF);
            this.#wsGeoTIFFStreamer.setRequestOptionsParams();
            this.#wsGeoTIFFStreamer.stream(result => {
                this.#msg = JSON.stringify({msg:verboseTag + 'xcx attachGeoTIFFAsOverlayForPath().',
                    result: result.blob,
                    result_: JSON.stringify(result),
                    type: typeof result,
                });
                console.log(this.#msg);
            })
            .then(res => {
                this.#msg = JSON.stringify({msg:verboseTag + 'xcx attachGeoTIFFAsOverlayForPath().',
                    result: res,
                    type: typeof res,
                });
                console.log(this.#msg);
                new GeoTIFF({
                    sources: [
                      {
                        blob: res,
                        overviews: ['https://openlayers.org/data/raster/no-overviews.tif.ovr'],
                      },
                    ],
                });
            });

        }
    }
}

stream:

stream(onResult) {
    return new Promise(async (resolve, reject) => {
        const ws = `${endPointsURLs.VUE_NEWSWM_APP_LOCAL_HOST_3000.description}${endPointsURLs.VUE_NEWSWM_APP_PATH.description}${BackendWssConstants.CONST_WS_GEOTIFF_STREAMER.description}/${this.#geoTIFFFileName}`;

        await fetch(ws, this.#requestOptions)
        .then(async response =>  {
            const b = await response.blob()
            console.log('xcx response: ', response)
            console.log('xcx Response status:', response.status);
            console.log('xcx Response headers:', response.headers);
            console.log('xcx blob: ', b)

            resolve(b);
            onResult(b);
        })
    });
}

screen-shot
enter image description here

Next.js – App Router – Add Content Security Policy Meta Tag in Head

In a Next.js app that uses App Router structure, I need to add a Content Security Policy (CSP) meta tag, like:

<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self'; img-src https://*; child-src 'none';" />

The problem:

The Metadata object described in docs does not have built-in support for Content-Security-Policy and also using the other field is not an option, since it renders meta tags only with name and content attributes:

export const metadata = {
  other: {
    csp: "default-src 'self'; img-src https://*; child-src 'none';",
  },
}
<meta name="csp" content="default-src 'self'; img-src https://*; child-src 'none';" />

The solution I’ve tried:

Add the <head> tag in the RootLayout (/app/layout.tsx):

export default function RootLayout({
  // Layouts must accept a children prop.
  // This will be populated with nested layouts or pages
  children,
  locale,
}: {
  children: ReactNode,
  locale: string
}) {
  return (
    <html lang={locale}>
      <head>
        <meta httpEquiv="Content-Security-Policy" content={csp} />
      </head>
      <body>
       {children}
      </body>
    </html>
  );
}

So far it seems to work. However, I was wondering if there is a more elegant solution for this.

Thanks.

Getting an error [ProtectedRoute] is not a component in a react app

In my react app, I am getting an error [ProtectedRoute] is not a component. I am using the below versions of react router

"react-router-dom": "^6.23.0",
"react": "^18.2.0"

Error details:

[ProtectedRoute] is not a component. All component children of must be a or <React.Fragment>
at invariant (http://localhost:3000/static/js/bundle.js:1473:11)
at http://localhost:3000/static/js/bundle.js:40454:108
at http://localhost:3000/static/js/bundle.js:42720:21

Here is my component details. Could someone please advise what could be the issue here ?

// protectedRoute.js

import React from 'react';
import { Route, Navigate } from 'react-router-dom';

const ProtectedRoute  = ({ isAuthenticated, element: Component, ...rest }) => {
  return (
    <Route {...rest} element={isAuthenticated ? <Component /> : <Navigate to="/login" replace />} />
  );
};

export default ProtectedRoute;

// index.js

import React, { useState, Fragment }from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import ReactDOM from 'react-dom';
import './index.css';
import Home from './client/components/home';
import About from './client/components/about';
import Login from './client/components/login';
import Admin from './client/components/admin';
import ProtectedRoute from './client/components/protectedRoute';

const App = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // Function to handle login
  const handleLogin = () => {
    setIsAuthenticated(true);
  };

  // Function to handle logout
  const handleLogout = () => {
    setIsAuthenticated(false);
  };

  return (
   
    <Router>
      <Fragment>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/login" element={<Login onLogin={handleLogin} />} />
        {/* <Route exact path='/' isAuthenticated={isAuthenticated} element={<ProtectedRoute/>}>
            <Route exact path='/' element={<Admin/>}/>
        </Route> */}
        <ProtectedRoute
          path="/admin"
          element={<Admin />}
          isAuthenticated={isAuthenticated}
        />
       </Routes> 
       </Fragment>
    </Router>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

// admin.js

const Admin = () => {
    return (
        <h1>Hello admin, finally you are here !</h1>
        
    )
};
export default Admin;

API response is not updating useState correctly

I’m hitting an API to return some data that I’m passing into a useState hook so I can map over that data and display to the user but for some reason the data does not update without a manual refresh. FYI I’m using Redux saga and Redux selectors to retrieve the data from state but that is besides the point. Here is snippets of the relevant code below:

import React, {useState} from 'react'

const BillingAddressDetails = () => {
  const activeAddresses = useAppSelector(getProfileActiveAddresses);
  const [sortedActiveAddresses, setSortedActiveAddresses] = useState([...activeAddresses]};
  
  return (
  sortedActiveAddresses.map(address => <BillingAddressCard={address} />
};

const BillingAddressCard = ({address}) => {
  return (
   <div>
     <span>{address.firstName} {address.lastName}</span>
     <span>{address.streetLine1}</span>
     <span>{address.city}</span>
   </div>
   )
}

I have a button that hits a PUT API to update a single address but after a successful API response, when I console.log activeAddresses I see the correct data and the correctly updated address, but if I console.log sortedActiveAddresses, I see the old data and the address that was updated is not updated. If I manually refresh the page then I get the correct data with the updated address. Also if I remove the useState completely and just map over the activeAddresses to give the BillingAddressCard components data to display, I get the same thing where I need to manually refresh to display the correct data. What am I missing here? Thank you for the help!

Version code of android fetch in ionic capacitor application

async getAppInfo() { const info = App.getInfo(); alert('App version:'+ (await info).version); }
this was not given version rather it displaying error
ERROR Error: Not implemented on web.
at AppWeb.unimplemented

Can some one help me on this your text
I need to fetch the version code in capacitor

I was trying to get the version code because I need to force to user to update the application

Event Listener Problem, Trouble Getting Images to Change

Having trouble getting images to change

I am having trouble getting the images to change on an event listener. The messages work fine but for some reason the images won’t change out when an event is triggered. I am a beginner with front end development and this is a self project I am doing. I followed along with this template but I do not know why it won’t work.
Template https://codepen.io/codifiedconcepts/pen/bwgxRq

Here are all the code associated with my project
https://github.com/LordCrusader1/Star-Wars-Clock-Official/blob/main/starwarsclock.js

Here is a visual of the issue I am dealing with and the associated images that the image should change to
https://youtu.be/qNyr109N2yY?si=NFTuk-oRtnwxIWUk

Not able to handle UI When Keyboard appears after clicking on textInput

So below is the code which works in ios without any disturbance in UI when keyboard Appears. But in Android, I have issues handling keyboard after clicking on textInput.

return (
        <View style={{
          flex: 1,
          backgroundColor: this.state.changeThemeSwitch ?
            helpers.whiteColor() : helpers.blackColor(),
          marginBottom: 10,
        }}>
          <CustomStatusBar />
          {this.renderHeader()}
          <View style={{
            justifyContent: "flex-end", alignItems: "flex-end",
            flex: 1,
          }}>

            <View
              style={{
                alignSelf: "flex-end",
                justifyContent: "flex-end", flexDirection: 'column',
                marginBottom: this.state.parentViewTopMargin,
                width: "100%",
              }}>

              <ScrollView
                ref={(ref) => this.scrollViewRef = ref}
                onLayout={() => {

                  if (this.scrollViewRef) {
                    this.scrollViewRef.scrollToEnd({ animated: false })
                  }
                }}
                keyboardShouldPersistTaps="handled">

                {messages &&
                  messages.map((item, index) =>
                    this.renderItem(item, index))}

              </ScrollView>

              <View style={{ ...styles.inputContainer }}>
                <TouchableOpacity onPress={this.showKeyboard}>
                  <FontAwesomeIcon
                    icon={faMicrophone}
                    size={30}
                    style={{
                      color: "#3A913F",
                    }}>
                  </FontAwesomeIcon>
                </TouchableOpacity>
                <TextInput ref={this.inputRef}
                  keyboardType='default'
                  multiline
                  style={{
                    flex: 1,
                    marginLeft: 10,
                    backgroundColor: this.state.changeThemeSwitch ? helpers.whiteColor() : helpers.blackColor(),
                    color: this.state.changeThemeSwitch ? helpers.blackColor() : helpers.whiteColor(),
                    borderRadius: 6,
                    paddingHorizontal: 16,
                    paddingVertical: 8,
                    marginRight: 10,
                    borderWidth: 1.5,
                    borderColor: "#3A913F"
                  }}
                  placeholder="Type your query..."
                  placeholderTextColor={this.state.changeThemeSwitch
                    ? helpers.blackColor()
                    : helpers.whiteColor()}
                  value={message}
                  onChangeText={(text) => this.setState({ message: text })}
                />
                <TouchableOpacity onPress={this.handleSend}>
                  <FontAwesomeIcon
                    icon={faPaperPlaneTop}
                    size={30}
                    style={{
                      color: "#3A913F",
                    }}>
                  </FontAwesomeIcon>
                </TouchableOpacity>
              </View>

            </View>
          </View>
        </View>
      );

I tried using KeyboardAvoidingView for android with behavior set as “padding” || “height”, but none of them worked.

Am I missing some styles for the mainView in render or Is there any other way to solve this issue in android?