getting function imported correctly in android but in ios gettting import value is null in react native module

While building this react-native module, i’m getting the function imported correctly in android and i’m able to get the result correctly but in ios when i log the default import i get null.

App.tsx (when used the rn-module in an example app)

import UniqueIdentifier from 'rn-unique-identifier/js/NativeUniqueIdentifier'
...
console.log("UniqueIdentifier", UniqueIdentifier)
console.log("UID", UniqueIdentifier?.getPersistentIdentifier())
...

Logs on Android:

LOG  Running "z" with {"rootTag":1,"initialProps":{"concurrentRoot":true},"fabric":true}
LOG  UniqueIdentifier {"getPersistentIdentifier": [Function getPersistentIdentifier]}
LOG  UID 82e8380c4fe6fc40922cd890f8388419eaf41ef63f12027cafed64ab8f129d0b

Logs on Ios:

LOG  Running "z" with {"rootTag":1,"initialProps":{"concurrentRoot":true},"fabric":true}
LOG  UniqueIdentifier null
LOG  UID undefined

NativeUniqueIdentifier.ts

import {TurboModule, TurboModuleRegistry} from 'react-native'

export interface Spec extends TurboModule {
    getPersistentIdentifier(): string
}

export default TurboModuleRegistry.get<Spec>('UniqueIdentifier') as Spec | null

RTNUniqueIdentifier.h

#import <RTNUniqueIdentifierSpec/RTNUniqueIdentifierSpec.h>

NS_ASSUME_NONNULL_BEGIN

@interface RTNUniqueIdentifier : NSObject <NativeUniqueIdentifierSpec>

@end

NS_ASSUME_NONNULL_END

RTNUniqueIdentifier.mm

#import "RTNUniqueIdentifierSpec.h"
#import "RTNUniqueIdentifier.h"
#import "Security/Security.h"
#import "UIKit/UIKit.h"

@implementation RTNUniqueIdentifier

RCT_EXPORT_MODULE()
- (NSString *)getPersistentIdentifier {
    NSDictionary *keychainQuery = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: @"MyAppDeviceId",
        (__bridge id)kSecReturnData: @YES
    };
    
    CFTypeRef keychainResult = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, &keychainResult);
    
    if (status == errSecSuccess) {
        // Device ID found in Keychain, return it
        NSData *keychainData = (__bridge_transfer NSData *)keychainResult;
        NSString *deviceId = [[NSString alloc] initWithData:keychainData encoding:NSUTF8StringEncoding];
        return deviceId;
    } else {
        // Device ID not found, generate a new one and store it in Keychain
        NSString *deviceId = [UIDevice currentDevice].identifierForVendor.UUIDString;
        
        if (!deviceId) {
            return nil;
        }
        
        NSData *deviceIdData = [deviceId dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *addQuery = @{
            (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
            (__bridge id)kSecAttrService: @"MyAppDeviceId",
            (__bridge id)kSecValueData: deviceIdData
        };
        
        OSStatus addStatus = SecItemAdd((__bridge CFDictionaryRef)addQuery, NULL);
        if (addStatus == errSecSuccess) {
            return deviceId;
        } else {
            return nil;
        }
    }
}


- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeUniqueIdentifierSpecJSI>(params);
}

@end

package.json

{
  "name": "rn-unique-identifier",
  "version": "1.0.1",
  "description": "Get persistent unique identifier in android & ios both",
  "react-native": "js/index",
  "source": "js/index",
  "files": [
    "js",
    "android",
    "ios",
    "unique-identifier.podspec",
    "!android/build",
    "!ios/build",
    "!**/__tests__",
    "!**/__fixtures__",
    "!**/__mocks__"
  ],
  "keywords": [
    "react-native",
    "ios",
    "android"
  ],
  "repository": "https://github.com/imtheaman/rn-unique-identifier.git",
  "author": "Aman Kumar <[email protected]>",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/imtheaman/rn-unique-identifier/issues"
  },
  "homepage": "https://github.com/imtheaman/rn-unique-identifier#readme",
  "devDependencies": {},
  "peerDependencies": {
    "react": "*",
    "react-native": "*"
  },
  "codegenConfig": {
    "name": "RTNUniqueIdentifierSpec",
    "type": "modules",
    "jsSrcsDir": "js",
    "android": {
      "javaPackageName": "pkg.uniqueidentifier"
    }
  }
}

rn-unique-identifier.podspec

require "json"

package = JSON.parse(File.read(File.join(__dir__, "package.json")))

Pod::Spec.new do |s|
  s.name            = "rn-unique-identifier"
  s.version         = package["version"]
  s.summary         = package["description"]
  s.description     = package["description"]
  s.homepage        = package["homepage"]
  s.license         = package["license"]
  s.platforms       = { :ios => "11.0" }
  s.author          = package["author"]
  s.source          = { :git => package["repository"], :tag => "#{s.version}" }

  s.source_files    = "ios/**/*.{h,m,mm,swift}"

  install_modules_dependencies(s)
end

UniqueIdentifierModule.java

package pkg.uniqueidentifier;

import androidx.annotation.NonNull;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import pkg.uniqueidentifier.NativeUniqueIdentifierSpec;
import android.media.MediaDrm;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class UniqueIdentifierModule extends NativeUniqueIdentifierSpec {

    public static String NAME = "UniqueIdentifier";

    UniqueIdentifierModule(ReactApplicationContext context) {
        super(context);
    }

    @Override
    @NonNull
    public String getName() {
        return NAME;
    }

    @Override
    public String getPersistentIdentifier() {
        UUID WIDEVINE_UUID = new UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L);
        MediaDrm wvDrm = null;

        try {
            wvDrm = new MediaDrm(WIDEVINE_UUID);
            byte[] widevineId = wvDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID);
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(widevineId);
            return bytesToHexString(md.digest());
        } catch (Exception e) {
            return null;
        } finally {
            if (wvDrm != null) {
                wvDrm.close();
            }
        }
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(0xFF & aByte);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

UniqueIdentifierPackage.java

package pkg.uniqueidentifier;

import androidx.annotation.Nullable;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.TurboReactPackage;

import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public class UniqueIdentifierPackage extends TurboReactPackage {

  @Nullable
  @Override
  public NativeModule getModule(String name, ReactApplicationContext reactContext) {
      if (name.equals(UniqueIdentifierModule.NAME)) {
          return new UniqueIdentifierModule(reactContext);
      } else {
          return null;
      }
  }


  @Override
  public ReactModuleInfoProvider getReactModuleInfoProvider() {
      return () -> {
          final Map<String, ReactModuleInfo> moduleInfos = new HashMap<>();
          moduleInfos.put(
                  UniqueIdentifierModule.NAME,
                  new ReactModuleInfo(
                          UniqueIdentifierModule.NAME,
                          UniqueIdentifierModule.NAME,
                          false, // canOverrideExistingModule
                          false, // needsEagerInit
                          true, // hasConstants
                          false, // isCxxModule
                          true // isTurboModule
          ));
          return moduleInfos;
      };
  }
}

folder structure:

├── android
│   ├── build.gradle
│   └── src
│       └── main
│           └── java
│               └── pkg
│                   └── uniqueidentifier
│                       ├── UniqueIdentifierModule.java
│                       └── UniqueIdentifierPackage.java
├── ios
│   ├── RTNUniqueIdentifier.h
│   └── RTNUniqueIdentifier.mm
├── js
│   ├── NativeUniqueIdentifier.ts
│   └── index.ts
├── node_modules
├── package.json
└── rn-unique-identifier.podspec

I tried searching the internet and raised issues in react-native repo discussion, but no luck.

Recreate a JS react system

everyone!

I would like to change the react system of a script I buy online.
Currently, the script has a react system to posts like Facebook and I would like to make it much simpler.

The Schema is pretty simple:
Like a button in black when there’s no reaction transforms into a colored one when the user presses it and reacts and turns back to black when the user presses it again(the colored one) and unreact to the post.

I would paste below all the lines from the JS file and the tpl file.

JS

// handle reactions
  function _show_reactions(element) {
    var _this = $(element);
    var reactions = _this.find('.reactions-container');
    var offset = _this.offset();
    var reactions_height = ($(window).width() < 480) ? 144 : 48;
    var posY = (offset.top - $(window).scrollTop()) - reactions_height;
    var posX = offset.left - $(window).scrollLeft();
    if ($('html').attr('dir') == "RTL") {
      var right = $(window).width() - posX - _this.width();
      reactions.css({ 'top': posY + 'px', 'right': right + 'px' });
    } else {
      reactions.css({ 'top': posY + 'px', 'left': posX + 'px' });
    }
    reactions.show();
  }
  function _hide_reactions(element) {
    var _this = $(element);
    var reactions = _this.find('.reactions-container:first');
    reactions.removeAttr('style').hide();
  }
  /* reactions toggle */
  $('body').on('mouseenter', '.reactions-wrapper', function () {
    if (!is_iPad() && $(window).width() >= 970) {
      /* desktop -> show the reactions */
      _show_reactions(this);
    }
  });
  $('body').on('mouseleave', '.reactions-wrapper', function () {
    if (!is_iPad() && $(window).width() >= 970) {
      /* desktop -> hide the reactions */
      _hide_reactions(this);
    }
  });
  $('body').on('click', '.reactions-wrapper', function () {
    if (is_iPad() || $(window).width() < 970) {
      /* mobile -> toggle the reactions */
      if ($(this).find('.reactions-container:first').is(":visible")) {
        /* hide the reactions */
        _hide_reactions(this);
      } else {
        /* hide any previous reactions */
        $('.reactions-container').removeAttr('style').hide();
        /* show the reactions */
        _show_reactions(this);
      }
    } else {
      /* desktop -> unreact */
      var _this = $(this);
      var old_reaction = _this.data('reaction');
      if (old_reaction) {
        if (_this.hasClass('js_unreact-post')) {
          var _undo = 'unreact_post';
          var handle = 'post';
          var _parent = _this.closest('.post, .lightbox-post, .article');
        } else if (_this.hasClass('js_unreact-photo')) {
          var _undo = 'unreact_photo';
          var handle = 'photo';
          var _parent = _this.closest('.post, .lightbox-post');
        } else if (_this.hasClass('js_unreact-comment')) {
          var _undo = 'unreact_comment';
          var handle = 'comment';
          var _parent = _this.closest('.comment');
        }
        var id = _parent.data('id');
        var reactions_wrapper = _parent.find('.reactions-wrapper:first');
        /* remove unreact from reactions-wrapper */
        reactions_wrapper.removeClass('js_unreact-' + handle);
        /* remove reactions-wrapper data-reaction */
        reactions_wrapper.data('reaction', '');
        /* change reaction-btn-name */
        _parent.find('.reaction-btn-name:first').text(__['Minused 1']).removeAttr('style');
        /* change reaction-btn-icon */
        _parent.find('.reaction-btn-icon:first').html('<i class="far fa-smile fa-lg fa-fw"></i>');
        /* hide reactions-container */
        _parent.find('.reactions-container:visible').removeAttr('style').hide();
        /* AJAX */
        $.post(api['posts/reaction'], { 'do': _undo, 'reaction': old_reaction, 'id': id }, function (response) {
          /* check the response */
          if (response.callback) {
            eval(response.callback);
          }
        }, 'json')
          .fail(function () {
            modal('#modal-message', { title: __['Error'], message: __['There is something that went wrong!'] });
          });
      }
    }
  });
  /* close reactions when clicked outside */
  $('body').on('click', function (e) {
    if ($(e.target).hasClass('reactions-wrapper') || $(e.target).parents('.reactions-wrapper').length > 0) {
      return;
    }
    $('.reactions-container').removeAttr('style').hide();
  });
  /* close reactions when user scroll (vertical) */
  var prevTop = 0;
  $(window).scroll(function (e) {
    var currentTop = $(this).scrollTop();
    if (prevTop !== currentTop) {
      prevTop = currentTop;
      $('.reactions-container').removeAttr('style').hide();
    }
  });
  /* react post & photo & comment */
  $('body').on('click', '.js_react-post, .js_react-photo, .js_react-comment', function (e) {
    e.stopPropagation();
    var _this = $(this);
    var reaction = _this.data('reaction');
    var reaction_color = _this.data('reaction-color');
    var reaction_title = _this.data('title');
    var reaction_html = _this.html();
    if (_this.hasClass('js_react-post')) {
      var _do = 'react_post';
      var _undo = 'unreact_post';
      var handle = 'post';
      var _parent = _this.closest('.post, .lightbox-post, .article');
    } else if (_this.hasClass('js_react-photo')) {
      var _do = 'react_photo';
      var _undo = 'unreact_photo';
      var handle = 'photo';
      var _parent = _this.closest('.post, .lightbox-post');
    } else if (_this.hasClass('js_react-comment')) {
      var _do = 'react_comment';
      var _undo = 'unreact_comment';
      var handle = 'comment';
      var _parent = _this.closest('.comment');
    }
    var id = _parent.data('id');
    var reactions_wrapper = _parent.find('.reactions-wrapper:first');
    var old_reaction = reactions_wrapper.data('reaction');
    /* check if user react or unreact */
    if (reactions_wrapper.hasClass('js_unreact-' + handle) && old_reaction == reaction) {
      /* [1] user unreact */
      /* remove unreact class from reactions-wrapper */
      reactions_wrapper.removeClass('js_unreact-' + handle);
      /* remove reactions-wrapper data-reaction */
      reactions_wrapper.data('reaction', '');
      /* change reaction-btn-name */
      _parent.find('.reaction-btn-name:first').text(__['React']).removeClass('blue red yellow orange');
      /* change reaction-btn-icon */
      _parent.find('.reaction-btn-icon:first').html('<i class="far fa-smile fa-lg fa-fw"></i>');
      /* hide reactions-container */
      _parent.find('.reactions-container:visible').removeAttr('style').hide();
      /* AJAX */
      $.post(api['posts/reaction'], { 'do': _undo, 'reaction': old_reaction, 'id': id }, function (response) {
        /* check the response */
        if (response.callback) {
          eval(response.callback);
        }
      }, 'json')
        .fail(function () {
          modal('#modal-message', { title: __['Error'], message: __['There is something that went wrong!'] });
        });
    } else {
      /* [2] user react */
      /* add unreact class to reactions wrapper */
      if (!reactions_wrapper.hasClass('js_unreact-' + handle)) {
        reactions_wrapper.addClass('js_unreact-' + handle);
      }
      /* change reactions-wrapper data-reaction */
      reactions_wrapper.data('reaction', reaction);
      /* change reaction-btn-name */
      _parent.find('.reaction-btn-name:first').text(reaction_title).removeAttr('style').css("color", reaction_color);
      /* change reaction-btn-icon */
      _parent.find('.reaction-btn-icon:first').html('<div class="inline-emoji no_animation">' + reaction_html + '</div>');
      /* hide reactions-container */
      _parent.find('.reactions-container:visible').removeAttr('style').hide();
      /* AJAX */
      $.post(api['posts/reaction'], { 'do': _do, 'reaction': reaction, 'id': id }, function (response) {
        /* check the response */
        if (response.callback) {
          eval(response.callback);
        }
      }, 'json')
        .fail(function () {
          modal('#modal-message', { title: __['Error'], message: __['There is something that went wrong!'] });
        });
    }
  });

tpl

<!-- post actions -->
        {if $user->_logged_in && $_get != "posts_information"}
        
          <div class="post-actions">
            <!-- reactions -->
            <div class="action-btn reactions-wrapper {if $post['i_react']}js_unreact-post{/if}" data-reaction="{$post['i_reaction']}">
              <!-- reaction-btn -->
              
              <div class="reaction-btn">
                {if !$post['i_react']}
                 <div class="reaction-btn-icon">
                  </div>
               
                {else}
               <div class="reaction-btn-icon">
                    <div class="inline-emoji no_animation">
                      {include file='__reaction_emojis.tpl' _reaction=$post['i_reaction']}
                    </div>
                  </div>
                {/if}
              </div>
              
              <!-- reaction-btn -->

                <div class="reaction-btn-icon">
                {foreach $reactions_enabled as $reaction}
                  <div class="reactions_item  reaction-{$reaction@iteration} js_react-post" data-reaction="{$reaction['reaction']}" data-reaction-color="{$reaction['color']}">
                    {include file='__reaction_emojis.tpl' _reaction=$reaction['reaction']}
                  </div>
                {/foreach}
              </div>
            </div>
            <!-- reactions -->

Please help me to transform it.
Thanks in advance.

Jquery function not working from a dynamic load content

I’m having a problem trying to make this additemtolist fuction to work, the id=clickitemtoadd is a list loaded dynamicly with avalible items. but because is Dynamic load is not working.

Here is the code for onclick call a function:

function additemtolist(pos_name,item_id,pos_value){
  alert('clicked')
}
<p id="clickitemtoadd" onclick="additemtolist('item name','item id','item sales value')">item name</p>

I can’t make a get request on the Api react native

I can’t make a get request on the Api

I tried to make an application that will show statistics of players in Dota, but I can’t make a request to the API,
I divided the main screen and the block where I connect the api to different files

(https://docs.stratz.com/api/v1/Player/1144302439)
error: undefined is not a functionenter image description here

    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
  
    import useApiHero from '../api/ApiHero';

    export const Main = () => {
    
        const { data } = useApiHero();

        data.map((post) => {
            return (
                <View style={styles.container}>    
                    <Text>{post.identity.captainJackIdentityId}</Text>
                </View>
            );
        })
    }

    const styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: '#222',
            alignItems: 'center',
            justifyContent: 'center',
        },
    });

    import { useState, useEffect } from 'react';

    export const useApiHero = () => {
        const [data, setData] = useState([]);
        const [loading, setLoading] = useState(true);
        const [error, setError] = useState(null);

        useEffect(() => {
            const fetchData = async () => {
                try {
                    const response = await fetch("https://docs.stratz.com/api/v1/Player/1144302439")
                    const json = await response.json();
                    setData(json);
                } catch (error) {
                    setError(error.message);
                } finally {
                    setLoading(false);
                }
            };

            fetchData();
        }, []);
    }

How Do I Update The Value of an Input Element Programmatically in React?

Let’s say I have a component that accepts an element (likely to be <input />) and I want to programmatically update the value of it after 15 seconds. This is my first thought on how to do it:

const MyComponent = (myInput: JSX.Element) => {
    useEffect(() => {
        setTimeout(() => {
            myInput instanceof HTMLInputElement && myInput.value = "new value";
        }, 15000);
    });   

    return <></>;
};

Now, this doesn’t work because myInput is a React Node / JSX Element and not a raw HTMLInputElement. To get around this my 2nd thought is to use ref somehow but myInput isn’t rendered so I’m unable to ref={myRef}.

Is there any way I can access the underlying HTML element at runtime?

My reason for this is because I’m using a library that has rather limited functionality and I’m trying to make it work correctly with react-hook-form. As RHF relies on onChange, I need to trigger a "change" event (I used myInput.value = above to simplify the example but really I just want the raw element to trigger an event)

Element type is invalid while integrating the webpack

ERROR
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

While integrating my project with webpack 5. I’m getting the above error.Can anyone please give me a solution for this.

I checked my export and import, everything is in correct way.But still it throws the same error.

How can I Prevent Blinking Issue in Real-Time Notification Dialog Box Triggered by Socket.io Events?

I am working on a JavaScript application that uses socket.io for real-time updates. I have a function that is triggered by a socket event (“to_client_a”), and it checks the distance between two markers. If the distance is less than or equal to 30, a notification dialog box is displayed.

socket.on("to_client_a", function (data) {
  console.log(`Received from B: ${JSON.stringify(data)}`);

  var dt = JSON.stringify(data);
  var newLatLng = new L.LatLng(data.Y, data.X);

  var marker1LatLng = marker1.getLatLng();
  var marker2LatLng = marker2.getLatLng();

  var distance = Math.sqrt(
    Math.pow(marker2LatLng.lat - marker1LatLng.lat, 2) +
      Math.pow(marker2LatLng.lng - marker1LatLng.lng, 2)
  );

  let dialogbox = document.getElementById("dialog-box");
  let timerBar = document.getElementById("timer-bar");

  console.log("Distance:", distance);
  if (distance <= 30) {
    mymap.removeLayer(marker1);
    dialogbox.classList.remove("display-box");
    dialogbox.classList.add("display-box");

    setTimeout(function () {
      dialogbox.classList.remove("display-box");
      dialogbox.classList.add("hidden-box");
      timerBar.style.width = "0";
    }, 4000);
    timerBar.classList.add("animate");
  }
  console.log("Received marker2 data:", dt);
});

The issue I’m facing is that when the socket receives new coordinates, the condition for displaying the dialog box is true, causing the dialog box to blink. It seems like the condition is being continuously evaluated with the new values.

I’ve tried to debug the issue, but I’m not sure how to prevent the dialog box from blinking. Any suggestions on how to handle this situation would be greatly appreciated.

Specifically, I expected that when the socket receives new coordinates, the condition (distance <= 30) would be evaluated once, and if true, the dialog box would be displayed without causing any blinking. Instead, it appears that the condition is continuously re-evaluating with the new values, resulting in the blinking behavior.

Saving audio data using GridFS

This code (see below) is only working partly and I need some help to fix it.

The function saveAudioToGridFS() is supposed to return a file ID to its calling function.

I can check that the value to be returned is properly computed (through the console.log(s)).

But due to some synchronization problems or something similar it is not passed to the calling side.

How can I fix this ? Any relevant tip is going to be welcome.

function saveAudioToGridFS(audioBlob) {
  const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db),
        writeStream = gridFSBucket.openUploadStream(getAudioName())

  // In the code below, writeStream.id.toString() is precisely what
  // should be returned to the calling function.
  writeStream.on('close', (file) => {
    console.log("saveAudioToGridFS.close-block")
    console.log("ID=",writeStream.id.toString())
    resolve(writeStream.id.toString())
  });

  writeStream.on('finish', (file) => {
    console.log("saveAudioToGridFS.finish-block")
    console.log("ID=",writeStream.id.toString())
    resolve(writeStream.id.toString())
  });

  writeStream.on('error', (error) => {
    console.log("saveAudioToGridFS.error-block")
    reject(error);
  });

  console.log("TRACE 1 : before createReadStream.")
  streamifier.createReadStream(audioBlob).
   pipe(writeStream)
  console.log("TRACE 2 : after createReadStream.")
} /* End of saveAudioToGridFS */


server.post('/upload', async (req, res) => {
  try {
    if (!req.body.audio) {
      return res.status(400).json({message: 'No audio data uploaded.'});
    }

    console.log("Before call to saveAudioToGridFS")
    const audioBuffer = Buffer.from(req.body.audio, 'base64'),
          fileId = saveAudioToGridFS(audioBuffer);

    console.log("fileId=",fileId) // The expected value is missing here.
    // Consequently the value of fileId is missing in the following code.

    // Create a new record object
    const newRec = new AppCollectn({
      channelID:req.body.channel,
      voiceRecordID:fileId,
      timeStamp: new Date().getTime()
    });

    // Insert the record in our MongoDB database
    await newRec.save();

    .....
    res.json({fileId});
  } catch (error) {
    console.error(error);
    res.status(500).json({
      message: 'An error occurred during upload.',
      error: JSON.stringify(error)
    });
  }
});

React infinite-scroll memory issue arises as the loaded data increases, especially with 20k+ posts containing videos and images

This happens when the loaded data gets to about 10000 posts with images/gifs

enter image description here

X formerly Twitter has the best infinite scroll I’ve seen so far I want to implement something similar but my UI has to be a grid so I can’t use something like [react-window](https://github.com/bvaughn/react-window).

I’ve also tried using react-intersection-observer to only show the elements if the list items are in view which brought the memory usage down quite a bit but it’s still using a lot of memory.

enter image description here

When min date is set to today, Date field is showing an error “Please enter a value greater than or equal to NaN.” on Magento

I am using Magento v2.4.0.

In certain forms, there’s a date field with a minimum value set to today using JavaScript. However, when the minimum value is set to today, the form shows an error saying ‘Please enter a value greater than or equal to NaN.’ I’ve checked my code but couldn’t find any errors. Any ideas on how to fix this?

HTML

<div class="bookTime__inputs--date">
    <label for="date">Date<sup>*</sup></label>
    <input type="date" name="appointment_date" placeholder="MM-DD-YYYY" data-validate="{'required-entry': true, 'validate-date': {dateFormat: 'YYYY-MM-DD'}}">
</div>

Script

require([
    'jquery',
    'mage/mage',
], function($) {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }

    today = yyyy + '-' + mm + '-' + dd;
    jQuery('#ask_a_specialist_form input[name="appointment_date"]').attr("min", today);
});

enter image description here

I tried to change the validation ways but could not figure it out.

getting error “TypeError: Router.use() requires a middleware function but got a undefined” while trying to import a router from other file

I am trying to write a router for all the user paths and exported it to use in index.js. When i try to use the userRouter in the index.js i am getting the error

C:UsersyugiOneDriveDocumentscodesNodeJsAPI_nodejsnode_modulesexpresslibrouterindex.js:469
      throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
      ^

TypeError: Router.use() requires a middleware function but got a undefined
    at Function.use (C:UsersyugiOneDriveDocumentscodesNodeJsAPI_nodejsnode_modulesexpresslibrouterindex.js:469:13)
    at Function.<anonymous> (C:UsersyugiOneDriveDocumentscodesNodeJsAPI_nodejsnode_modulesexpresslibapplication.js:227:21)
    at Array.forEach (<anonymous>)
    at Function.use (C:UsersyugiOneDriveDocumentscodesNodeJsAPI_nodejsnode_modulesexpresslibapplication.js:224:7)
    at Object.<anonymous> (C:UsersyugiOneDriveDocumentscodesNodeJsAPI_nodejsindex.js:22:5)

but when i export it in this format

module.exports = {
userRouter:router
}

everything works file without any problem.

there is one other router file for api paths in routes, I removed that file to see if it is the problem but the error still persisted.

This is the user router i wrote

const express = require('express');
const router = express.Router();
const { getAllUsers, createNewUser, getUserById, updateUserData, deleteUser } = require('../controllers/userController')

router.use(express.json())
router.use(express.urlencoded({ extended: false }))

router.route('/')
    .get(getAllUsers)
    .post(createNewUser)

router.route('/:id')
    .get(getUserById)
    .patch(updateUserData)
    .delete(deleteUser)


module.exports = router

index.js file

//imported files

require('dotenv').config()
const express = require('express');
const { getConnection } = require('./connection')
const app = express();
const PORT = process.env.PORT || 8080
const { userRouter } = require('./routes/userRoutes')

//connection

try {
    getConnection
    console.log('connected to db');
}
catch (error) {
    console.log(error)
}

//middleware
// console.log(apiRouter)
app.use("/users", userRouter);

//listening 

app.listen(PORT, () => {
    console.log(`server started on http://localhost:${PORT}`)
})

In the fullstack development , how we can return a boolean value from spring boot side to js side [duplicate]

This is the java script side

fetch(`http://localhost:8080/logIn/?userName=`+userName+`&password=`+password , {
    method:"POST"
});

This is the spring boot side

@PostMapping("/logIn/")
Boolean logIn(@RequestParam String userName , String password) throws SQLException, ClassNotFoundException {
    System.out.println("Hello");

    Connection connection = DBConnection.getInstance().getConnection();
    PreparedStatement pstm = connection.prepareStatement("SELECT * FROM librarians");
    ResultSet resultSet = pstm.executeQuery();
    while(resultSet.next()) {
        String userName2 = resultSet.getString(1);
        String password2 = resultSet.getString(2);

        if (userName.length() == userName2.length()) {
            int count = 0;

            for (int i = 0; i < userName.length(); i++) {
                if (userName.charAt(i) == userName2.charAt(i)) {
                    count++;
                }
            }

            if (count == userName.length()) {
                if(password.length() == password2.length()){
                    int count2 = 0;

                    for(int j = 0; j<password.length(); j++){
                        if(password.charAt(j) == password2.charAt(j)){
                            count2++;
                        }
                    }

                    if(count2 == password.length()){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    return null;
}

This is my fetch
What are the changes to print a boolean value which is came from spring boot side after calling fetch

API NODE JS port, server [closed]

I have a question, I have designed APIS but always using a server and a port, if in case I already have a web server, for example, where is my route www.example.com, in my api.js code I should include the port and create the server? What I don’t understand is how to make the code work only if you enter the url www.example.com/api/users
and that is not www.localhost:3000/api/users. please help me thank you

I don’t know how to do this…

useRoute redirectedFrom is undefined when redirecting using navigateTo in Nuxt 3

I am using navigateTo to change pages like so:

navigateTo('/app/documents/all-documents')

After successfully getting to that page I am trying to implement a breadcrumb to go back to the previous route. However, useRoute’s redirectedFrom is undefined

const route = useRoute()
console.log(route.redirectedFrom) //undefined

I don’t know if my doing navigateTo correctly or if I misunderstood the use of redirectedFrom.

Nuxt3 Docs
https://nuxt.com/docs/api/composables/use-route

Is it possible to unload a fetched JSON file from a web browser? [duplicate]

I have a web application that loads very large JSON files via the fetch() api, but there does not seem to be a way to clear them from memory when the program no longer needs them. Is there a method of dynamically unloading fetched files from system memory to prevent poor performance? I am aware that resetting the variable clears the JSON from it, but the file still lingers in memory.
The method I am using to get JSON files is simply var JSONvar = fetch(http://api.website.com/files/JSONfile.json)

I have tried searching online for any solutions and have come across methods for unloading/reloading javascript files (discussed here) directly embedded in the HTML document, but I do not believe a similar method exists for JSON loaded into javascript variables. I am aware that window.onunload exists, but I am not sure how to force anything to unload.