Jquery dialog error with Datatables not rendering background

I have run across some issues while trying to implement Datatable on a dialog popup.
Below is my code:
HTML Code

<a href="#" onclick="loadData();"><span class="onlineCounter bigtext">Show Counter</span></a></div>

<div id="loadCounterInfo" style="min-height:400px; height: 450px;">
    <table id="loadCounterTable">
        <thead>
            <tr>
                <th>Vehicle Name</th>
                <th>Time</th>
            </tr>
        </head>
        <tbody>
            <tr>
                
            </tr>
        </tbody>
    </table>
</div>

My Javascript code for dialog below:

$("#loadCounterInfo").dialog({
        autoOpen: false,
        width: "450",
        height: "550",
        minHeight: "500",
        resizable: false,
        close: function(e, ui){
            console.log("Closed LoadCounterInfo");
        },
        open: function(){
          loadDatatableInfo();
            console.log("Opened LoadCounterInfo");
        }
    });

I have two javascript functions:

function loadData(){
    
    $('#loadCounterInfo').dialog('open');
      
}
function loadDatatableInfo(){
    var tabl = $('#loadCounterTable').DataTable({
        paging: true,
        scrollY: 300,
        retrieve: true,
        ajax: {
            url: "func/fn_dashboard.php?cmd=load_online_info"
        },
        columns: [
            {data: 'veh_name'},
            {data: 'status_time'}
        ]
    });
}

When ever I click the Show Counter link, A dialog is created as desired and console.log(“Open LoadCounter”) shows on the console, likewise when I close it.
Dialog with Datatable working Ok

If I should close the dialog and open it for the second time, I experience a transparent background and the dialog does not load properly, The Datatable information is still loaded but seems overlayed, I do not understand what is going on here.
Dialog with Datatable transparent background
if I should comment out the loadDatatableInfo, only the dialog works perfectly well even when i close and open it hundreth time..Only dialog box

How to connect to Microsoft SQL Server from Azure Functions using JavaScript?

We´re developing a function app in JavaScript with the Serverless Framework and deploying it to Azure.

We´re pulling data from a Microsoft SQL Server 2014 database, everything goes well when testing the functions in a local environment with the Serverless Offline plugin and a VPN. This is the code to establish the connection:

const mssql = require("mssql");

const sqlConfig = {
  user: process.env["DB_USER"],
  password: process.env["DB_PWD"],
  database: process.env["DB_NAME"],
  server: process.env["DB_HOST"],
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000,
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false, // change to true for local dev / self-signed certs
  },
};

// pool-manager.js
const pools = new Map();

module.exports = {
  get: (name) => {
    if (!pools.has(name)) {
      const pool = new mssql.ConnectionPool(sqlConfig);
      // automatically remove the pool from the cache if `pool.close()` is called
      const close = pool.close.bind(pool);
      pool.close = (...args) => {
        pools.delete(name);
        return close(...args);
      };
      pools.set(name, pool.connect());
    }
    return pools.get(name);
  },

  closeAll: () =>
    Promise.all(
      Array.from(pools.values()).map((connect) => {
        return connect.then((pool) => pool.close());
      })
    ),
};

We´re also using Key Vault’s references, these are working normally.

The problem is when the functions are deployed, the connections to the database is never established. This is the error I get:

{
  "code": "ESOCKET",
  "originalError": {
    "code": "ESOCKET"
  },
  "name": "ConnectionError"
}

So, my questions is: What has to be done in Azure or what has to be changed in our code to allow this connection?

Thanks

How i can change UI on change redux-toolkit state?

I want to rerender my component when i’m dispatch from another component, how i can do it?

Component that need for rerender:

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages({
            messages: message
        })
        console.log(message)
    }, message);



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}

Preventing React from clearing dropdown menus housed in a child component after a re-render

I’m building a search component. I have an API endpoint to which I can add searchParams depending on what dropdown the user chooses. It also makes separate call to find out what dropdown content will include.

So a user could type in “Audi” and then the dropdowns would be pre-filled with various options like “Engine Type” – but they’re optional.

The result is a response from an API containing an array of all matching vehicles. Pretty simple.

What’s interesting is that the dropdowns live in their own <AdvancedDropdowns> component. On page load, the parent <Search /> which houses ` passes down the recently retrieved options, populating them upon initial render. In other words, now the dropdowns have “V4, V8” etc as options for, say, Engine dropdown.

I’m passing a handler to <AdvancedDropdowns /> so that when a user picks, say, V8 as a dropdown option, I need to do another call in real-time to the original API point except the url looks more like this: api.com/?query=audi&engine=v4. This will re-render the list but it will also re-render the child <AdvancedDropdowns /> component and thus clear out the selections.

The problem is that if they make even one selection, the handler will run, the now modified URL will be called, and as the list re-renders it’s impossible to select more than one dropdown at a time because by selecting even one, the re-render clears out the list.

I’ve been thinking about using the re-render as an opportunity to pass the recorded selections back to the dropdown and let it set its defaults to what was already selected as it’s being re-rendered but it seems a little strange.

Here’s the behavior I’d like to see:

  • User types something in the search box? Hit the API and show a new list
  • User types something in, gets new list, then chooses a dropdown? Hit the API and get another list
  • User types something in, gets new list, chooses two dropdowns? Hit the API once per dropdown (three times total at this point)

The idea is to feel as responsive of a “filter” as possible but I’m struggling since re-rendering clears out the previous dropdown selections.

Hope that makes sense.

Any advice would be appreciated.

Requesting permission for location with a pop up window / using javascript code / then submiting it within a form

This code works perfect, although its accuracy aint 100% but good enough for now. i cant find a way to bring the results of this code into either php or in a html form.

And i need permission from the person arriving for their location.

How can i bring upon a pop up window using this code and then submiting the results to a html form so i can use:

$_POST[“state”];

var country = document.getElementById('country');
    var state = document.getElementById('state');
    var city = document.getElementById('city');
    var postal = document.getElementById('postal');
    var latitude = document.getElementById('latitude');
    var longitude = document.getElementById('longitude');
    var ip = document.getElementById('ipv4');

    function callback(data)
    {
        country.innerHTML = data.country_name;
        state.innerHTML = data.state;
        city.innerHTML = data.city;
        postal.innerHTML = data.postal;
        latitude.innerHTML = data.latitude;
        longitude.innerHTML = data.longitude;
        ip.innerHTML = data.IPv4;
    }

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://geolocation-db.com/json/geoip.php?jsonp=callback';
    var h = document.getElementsByTagName('script')[0];
    h.parentNode.insertBefore(script, h);

Android App crashed on pressing signup button

I have tried to create an login and registration form in VS Code with firebase Authentication service. So i added firebase dependencies to the build gradle and run the app, When i click the login or register button ,Data base updated with data but the app crashes. Also No error log on terminal.
Please some one help me out as i am stuck here since a week and did almost everything what i can.
Will be greatfull for your kind support
This is my Signup page code

import React,{useState} from 'react'
import { View, Text,Image,StyleSheet,KeyboardAvoidingView,TouchableOpacity,Alert} from 'react-native'
import {TextInput,Button} from 'react-native-paper'
import auth from '@react-native-firebase/auth';


const Loginscreen = ({navigation}) => {
    const [email,setemail]=useState('')
    const [password,setpassword]=useState('')
    const userSignup=async ()=>{
        if(!email||!password)
        {Alert.alert('Email or password is missing !')
    return
    }
    try{
        await auth().createUserWithEmailAndPassword(email,password)    
    }
    catch(err)
    {
        Alert.alert('Failure !')
    }
    
    }
  return (
    <KeyboardAvoidingView behavior='position'>
        <View style={styles.box_1}>
         <Image style={{width:200,height:200}} source={require('../assets/logo.png')} />
        <Text style={styles.loginmessage}>
            Please Sign Up to Continue...
        </Text>
        </View>
        <View style={styles.box_2}>
        <TextInput label='Email'
         value={email} 
         mode='outlined'
         onChangeText={text=>setemail(text)}/>
         <TextInput label='Password'
         value={password}
         mode='outlined'
         secureTextEntry={true}
         onChangeText={text=>setpassword(text)}
         
         />
          <Button mode="contained" onPress={() => userSignup()}>
    Sign Up
  </Button>
  <TouchableOpacity onPress={()=>navigation.navigate('Login')}><Text style={{textAlign:'center'}}>Log In ?</Text></TouchableOpacity>
        </View>
      
        </KeyboardAvoidingView>
  )
}

This is my app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
apply plugin: 'com.google.gms.google-services'



/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and that value will be read here. If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.olxfirebase"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

        if (isNewArchitectureEnabled()) {
            // We configure the NDK build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                ndkBuild {
                    arguments "APP_PLATFORM=android-21",
                        "APP_STL=c++_shared",
                        "NDK_TOOLCHAIN_VERSION=clang",
                        "GENERATED_SRC_DIR=$buildDir/generated/source",
                        "PROJECT_BUILD_DIR=$buildDir",
                        "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                        "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build"
                    cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
                    cppFlags "-std=c++17"
                    // Make sure this target name is the same you specify inside the
                    // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
                    targets "olxfirebase_appmodules"

                    // Fix for windows limit on number of character in file paths and in command lines
                    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                        arguments "NDK_OUT=${rootProject.projectDir.getParent()}\.cxx",
                            "NDK_APP_SHORT_COMMANDS=true"
                    }
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            ndkBuild {
                path "$projectDir/src/main/jni/Android.mk"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureNdkBuild* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureNdkBuildRelease.dependsOn(preReleaseBuild)
            configureNdkBuildDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
     implementation 'androidx.multidex:multidex:2.0.1'
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"



    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid")).because("On New Architecture we're building React Native from source")
        }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

this is my Project-level Build.Gradle Code

import org.apache.tools.ant.taskdefs.condition.Os

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "31.0.0"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31

        if (System.properties['os.arch'] == "aarch64") {
            // For M1 Users we need to use the NDK 24 which added support for aarch64
            ndkVersion = "24.0.8215888"
        } else if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            // For Android Users, we need to use NDK 23, otherwise the build will
            // fail due to paths longer than the OS limit
            ndkVersion = "23.1.7779620"
        } else {
            // Otherwise we default to the side-by-side NDK version from AGP.
            ndkVersion = "21.4.7075529"
        }
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.0.4")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath("de.undercouch:gradle-download-task:4.1.2")
        classpath 'com.google.gms:google-services:4.3.10'
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup "com.facebook.react"
            }
        }
        google()
        maven { url 'https://www.jitpack.io' }
    }
}

How to fix missing dependency warning when using useEffect React Hook? I am using nextjs app

The warning I am getting:

Warning: React Hook useEffect has a missing dependency: 'router'. Either include it or remove the dependency array

And the code I write in _app.js:

 const router = useRouter();
  useEffect(() => {
    router.events.on('routeChangeStart', ()=>{
      setProgress(40)
    })
    router.events.on('routeChangeComplete', ()=>{
      setProgress(100)
    })
    // console.log("I am refreshed!")
   try {
    if(localStorage.getItem("cart")){
      setcart(JSON.parse(localStorage.getItem("cart")))
      saveCart(JSON.parse(localStorage.getItem("cart")))
    }
   } catch (error) {
     console.error(error)
     localStorage.clear()
   }
   let token = localStorage.getItem("token");
   if(token){
     setuser({value: token})
     setkeyMaker(Math.random())
   }
  
  }, [router.query])

and I have also imported {useEffect} and {useRouter} from react!
Please help me to sort this issue out!

How to make a shorter ternary conditional operator in a React functional component?

I made a countdown timer in React using useState and useEffect hooks; everything is working great however the ternary conditional operator for seconds, where I am prepending 0 and replacing the counter value 0 with 00 for display purposes seems a bit excessive. Is there a way to simplify/shorten this, maybe setting Math.floor((counter % (1000 * 60)) / 1000) to a variable in the return ()? Not sure how to do this in React.

return (
  <div className={styles.timer}>
    <span className={styles.minutes}>
      {Math.floor((counter % (1000 * 60 * 60)) / (1000 * 60))}
    </span>
    <span className={styles.colon}>:</span>
    <span className={styles.seconds}>
      {Math.floor((counter % (1000 * 60)) / 1000) === 0 ?
      `00` :
      Math.floor((counter % (1000 * 60)) / 1000) < 10 ?
      `0${Math.floor((counter % (1000 * 60)) / 1000)}` :
      Math.floor((counter % (1000 * 60)) / 1000)
      }
    </span>
  </div>
)

Mongodb Random Data from aggregate function with Bias

Does mongodb aggragate function support biases or will favor values that are specified, for example i have an array of values for a variable

genre = [science, math, english]

and I want to get (5) random document from the database where the document has a either 1 of the genres in the specified array, I want to get these data from biases since if ever that only 2 documents matched the specified condition, i want the other 3 to be randomized instead, thus completing the 5 random documents that i need.

Heres what i’ve gotten so far, but it only gets random data without any values

    const book = await Book.aggregate([

        {
            $match: { genre: { $type: "string" } }
        },
        {

            $sample: { size: 6 }
        },
        {
            $set: {
                genre: {
                    $cond: {
                        if: { $eq: [{ $type: "$genre" }, "string"] },
                        then: ["$genre"],
                        else: "$genre"
                    }
                }
            }
        },
    ]);

Best Practice for Route Architecture

I’m trying to set up routes for my backend. I have two ways that I’ve tried setting these routes up, and I’m wondering which way fits best practices (or neither?). The differences are minimal, but I’d love to know if there is an objective “best” here.

Here are my attempts:

const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');

router.get('/', flashcardController.readFlashcard);
router.post('/', flashcardController.createFlashcard);
router.patch('/', flashcardController.updateFlashcard);
router.delete('/', flashcardController.deleteFlashcard);

module.exports = router

VS

const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');


module.exports = (app) => {
    router.get('/api/flashcard', flashcardController.readFlashcard);
    router.post('/api/flashcard', flashcardController.createFlashcard);
    router.patch('/api/flashcard', flashcardController.updateFlashcard);
    router.delete('/api/flashcard', flashcardController.deleteFlashcard);

    app.use('/', router);
};

Of course, my app.js (entry-point for my backend) file will need to be coded slightly differently for each of these options.

Destructuring array of arrays to get access to individual elements

So, I am working with an array of arrays like this:

const arrOfArrs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

For my example problem, I can only access the individual elements by using a nested loop,
I’d like to be able to (if possible) use a single loop, using destructuring to access the individual elements of each sub-array

Example (I know this works somewhat but not as intended): I need access to each element. And it needs to be flexible. In case I’m working with different sized arrays. (3 x 3 or 4 x 4 etc.) Writing the el1, el2, el3 wouldn’t be flexible for other sized array of arrays

 arrOfArrs.forEach(([el1, el2, el3]) => console.log(el1));

Above would console log each first el of each sub array: example el1 would log: 1, 4 , 7. I’d like to get individual element 1, then 2, 3, 4 etc. And be able to loop through it all. Is this possible?

Thank you so much for your help!

How to add objects from a fetch request to a local object based on matching keys in React?

I am having trouble updating the data in an object.
I have an object A, which I am importing from a JS file, and its structure is:

A = [
      {"id": 1, "name": "test", "project": {}},
      {"id": 2, "name": "test2", "project": {}},
      {"id": 3, "name": "test3", "project": {}},
      {"id": 4, "name": "test4", "project": {}}
    ]

I am then fetching data from the backend, and the structure is:

data = [
         {"id":1, "user": "test", "something": "test", ...},
         {"id":2, "user": "test", "something": "test", ...},
       ]

I want to add each object from data to A’s project based on matching id.
I tried the following, but the data is not getting passed. In the following code, projectData is A, and result is data.

const finalObject = [];

useEffect(()=>{
      fetch("http://localhost:2020/projects")
      .then((res) => {
        if (res.ok){
          return res.json();
        }
        throw new Error('Failed to fetch data.');
      })
      .then((result)=>{
        projectData.forEach((item) => {
          var newItem = {...item};
          result.forEach((item2) => {
            if (item.id == item2.id) {
              newItem = {...newItem, "project": item2};
            }
          })
          finalObject.push(newItem);
        })
      })
      .catch((error) => {
        console.log(error.message);
        console.log('Back-end is offline');
      })
    }, []);

What am I doing wrong?

Make New Array which is combination of other Two

I Have Two Array, One is normal one where dates values are being stored

    var = [
    "2022-05-01",
    "2022-05-02",
    "2022-05-03",
    "2022-05-04",
    "2022-05-05",
    "2022-05-06",
    "2022-05-07",
    "2022-05-08",
    "2022-05-09",
    "2022-05-10",
    "2022-05-11",
    "2022-05-12",
    "2022-05-13",
    "2022-05-14",
    "2022-05-15",
    "2022-05-16",
    "2022-05-17",
    "2022-05-18",
    "2022-05-19",
    "2022-05-20",
    "2022-05-21",
    "2022-05-22",
    "2022-05-23",
    "2022-05-24",
    "2022-05-25",
    "2022-05-26",
    "2022-05-27",
    "2022-05-28",
    "2022-05-29",
    "2022-05-30"
]

The other one is objects of Array where two objects are present

    var b = [
  {
    "k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
    "v_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
    "key": "Testing",
    "value": "999",
    "start_date": "2022-05-06T00:00:00.000Z",
    "end_date": "2022-05-06T00:00:00.000Z"
  },
  {
    "k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
    "v_id": "ad95cc4a-ec72-4d6e-a452-f519358f265d",
    "key": "Testing",
    "value": "189",
    "start_date": "2022-05-08T00:00:00.000Z",
    "end_date": "2022-05-`enter code here`08T00:00:00.000Z"
  }
]

My Requirement is to Convert new array into like this

[
{
    "value": "",
    "value_id": "",
    "date": "2022-05-01"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-02"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-03"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-04"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-05"
},
{
    "value": "999",
    "value_id": "48138929-6848-4ffe-86ce-183c75d021b4",
    "date": "2022-05-06"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-07"
},
{
    "value": "189",
    "value_id": "06c4f66f-efae-4981-bebd-6734addab4a5",
    "date": "2022-05-08"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-09"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-10"
},
{
    "value": "",
    "value_id": "",
    "date": "2022-05-11"
}

]

Like in the object 2022-06-11 data is there, so the new array will consist an object which will have properties related to that object. Similar to if the object has start_date present which is also in date array, so the new array will consist object for those info. Otherwise it will create blank object respective to date.

But I am able to come with this

[
{
    "value": "999",
    "value_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
    "date": "2022-05-06"
},
{
    "value": "189",
    "value_id": "ad95cc4a-ec72-4d6e-a452-f519358f265d",
    "date": "2022-05-08"
},
{
    "value": "",
    "date": "2022-05-03"
},
{
    "value": "",
    "date": "2022-05-04"
},
{
    "value": "",
    "date": "2022-05-05"
},
{
    "value": "",
    "date": "2022-05-06"
},
{
    "value": "",
    "date": "2022-05-07"
},
{
    "value": "",
    "date": "2022-05-08"
},
{
    "value": "",
    "date": "2022-05-09"
},
{
    "value": "",
    "date": "2022-05-10"
},
{
    "value": "",
    "date": "2022-05-11"
},
{
    "value": "",
    "date": "2022-05-12"
},
{
    "value": "",
    "date": "2022-05-13"
},
{
    "value": "",
    "date": "2022-05-14"
},
{
    "value": "",
    "date": "2022-05-15"
},
{
    "value": "",
    "date": "2022-05-16"
},
{
    "value": "",
    "date": "2022-05-17"
},
{
    "value": "",
    "date": "2022-05-18"
},
{
    "value": "",
    "date": "2022-05-19"
},
{
    "value": "",
    "date": "2022-05-20"
},
{
    "value": "",
    "date": "2022-05-21"
},
{
    "value": "",
    "date": "2022-05-22"
},
{
    "value": "",
    "date": "2022-05-23"
},
{
    "value": "",
    "date": "2022-05-24"
},
{
    "value": "",
    "date": "2022-05-25"
},
{
    "value": "",
    "date": "2022-05-26"
},
{
    "value": "",
    "date": "2022-05-27"
},
{
    "value": "",
    "date": "2022-05-28"
},
{
    "value": "",
    "date": "2022-05-29"
},
{
    "value": "",
    "date": "2022-05-30"
}

]

It is taking only first entry and printing and rest are coming as blank.

My Code: –

var a = {};
          dateArr = [];
          for (var j = 0; j < this.date_val.length; j++) {
            debugger;
              var b = {}
              console.log(val2.value[j]);
              
              if (val2.value.length > 0) {
                const newKey = this.date_val[j];
                b[newKey] = val1.data;
                // if (
                //   moment(val2.value[j].start_date).format("YYYY-MM-DD") !=
                //   this.date_val[j]
                // ) {
                //   this.vala = val2.value[j].value;
                //   this.valb = val2.value[j].val_id;
                //   this.valc = moment(val2.value[j].start_date).format(
                //     "YYYY-MM-DD"
                //   );

                // } 

                // if (
                //   moment(val2.value[j].start_date).format("YYYY-MM-DD") !=
                //   this.date_val[j]
                // ) {
                  a = {
                    value:
                      val2.value[j] != undefined ? val2.value[j].value : "",
                    value_id:
                      val2.value[j] != undefined
                        ? val2.value[j].v_id
                        : undefined,
                    date:
                      val2.value[j] != undefined
                        ? moment(val2.value[j].start_date).format(
                            "YYYY-MM-DD"
                          )
                        : this.date_val[j],
                  };
                // }
                
              } else {
                a = {
                  value: "",
                  value_id: undefined,
                  date: this.date_val[j],
                };
              }
            dateArr.push(a);
          }
          this.nameArray.push({
            key: val1.key,
            key_val: val1.id,
            date: dateArr,
          });

Can someone please help me with this? Thanks in Advance.