Confusion around useEffect dependency and how to re-design this approach

I happen to be using two different effects that are almost identical.

relevant state:

   const [selectedId, setSelectedId] = React.useState(""); 
   const [refreshData, setRefreshData] = React.useState(false); 

Effects:

  1. Go get new data only when the selectedId state changes and isn’t empty (too avoid excessive calls):
   React.useEffect(() => {
      const getData = async() => {
         const data = await getA(selectedId);
         setData(data);
      }

      if (selectedId.length > 0) {
         getData();
      }

   }, [selectedId])
  1. After certain actions and updates in the page, I want to call the same endpoint for my data, but in this case I need to do one additional and critical thing which has to do with setting up the UI. Call it: clearSomeUI()
   React.useEffect(() => {
      clearSomeUI(); // this resets some piece of ui, it's important

      const getData = async() => {
         const data = await getA(selectedId);
         setData(data);
      }

      if (selectedId.length > 0) {
         getData();
      }

   }, [refreshData])

I created the refreshData boolean state to trigger a refresh of my grid so it’ll reflect what’s on the server after a save. For example, when I’m done saving a record I would say setRefreshData(!refreshData). That’s the only way I could figure out how to force a re-fetch whenever I want.

But this is actually working. It refreshes when I want it to and it runs the other one that has the additional function when I want. Maybe I just haven’t had the opportunity to see stale data but so far it seems good. How am I supposed to obey the es lint dep rules and still achieve what I want? There must be a more elegant way to refresh data.

I know that the eslint rules would yell at me here suggesting I need both selectedId and refreshData in the dependency array of both. But if I added both, it would always run that function clearSomeUI(). At the same time, it feels like I shouldn’t even have different effects either.

Is there a way to look for a specific value of state (ie, not invert it) but just check the condition within the effect on whether or not I want to call that extra function? And then where would I reset it back? I mean, I can’t set it to true and then look to see if it’s true and then set it back to false if it is, within the effect. Something like:

   React.useEffect(() => {
      if (refreshData) {
         clearSomeUI();
         setRefreshData(false);
      }
       

      const getData = async() => {
         const data = await getA(selectedId);
         setData(data);
      }

      if (selectedId.length > 0) {
         getData();
      }

   }, [refreshData, selectedId])

Is it a good thing to check if a module is found in Window before requiring it?

I recently wanted to import one of my packages from NPM to a HTML file, but it said require wasn’t defined (Because it doesn’t exist), currently, on the top of my npm package i have

const ws = require("ws");
const Utils = require("utilsbox");

Should i change it to

const ws = document.ws !== null && document.ws !== undefined ? document.ws : require("ws");
const Utils = document.utilsbox !== null && document.utilsbox !== undefined ? document.utilsbox : require("utilsbox");

Or is there a better way

Why non async function is running asyncronus?

I have a function that must validate some artist from spotify API, but when i run it artists[] remains empty because the function is running asyncronusly, it fills the variable user without having set artists.

      let artists=[]

function setArtists(input) {
artists.length=0
let parsedInput = input.value.split(",")
parsedInput.forEach(artist =>{
    validateArtist(artist)
})
}





function validateArtist(s) {
let token = localStorage.getItem("Token")
let url="https://api.spotify.com/v1/search?type=artist&q="+s
console.log(url)
fetch(url, {
"method": "GET",
"headers": {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "Bearer "+token,
}
})
.then(response=>{
    if (response.status===401){
        refreshToken(s)
    } 
    return response.json()
})
.then(searchedResults=>searchedResults.artists.items.length!=0)   
.then(isArtist=>{
    if (isArtist){
        artists.push(s)
    }
})}

Here is were i call the function, i call it before so it can fill artists

setArtists(document.getElementById("artistiPreferiti"))
    var user = {
            username: document.getElementById("username").value,
            email: document.getElementById("email").value,
            password: document.getElementById("password").value,
            gustiMusicali: document.getElementById("gustiMusicali").value,
            artistiPreferiti: artists
    }    
 

What am i missing?

auto width any element using input tag

I’m making an iframe size generator where if they type a number from the input tag with the minimum width of 300px to 600px only. If a user types a number, it should be change syncronize with the iframe’s width size

here’s my HTML code

<div class="ecp">
    <div class="e">
        <div class="pi-b1">
            <div class="pi-b2">
                <div class="pi-b3">
                    <div class="pi-b4 iframe">
                        <iframe src="https://rarefrostbites.pages.dev/store/com.rarefrostbites.8.1st_century.html" id="iframe" title="1st Century - RareFrostbites Team | RFB Store" loading="lazy" frameborder="0"></iframe>
                    </div>
                </div>
            </div>
        </div>
        <div class="pi-b1">
            <div class="pi-b2">
                <div class="pi-b3">
                    <div class="pi-b4 controller">
                        <div class="opt">
                            <div class="width">
                                <h4>width</h4>
                                <input type="number" name="width" value="320" min="300" max="600" id="e_width">
                            </div>
                            <div class="height">
                                <h4>height</h4>
                                <input type="number" name="height" value="400" min="400" max="800" id="e_height">
                            </div>
                        </div>
                        <div class="btn">
                            <button>
                                <img src="https://rarefrostbites.pages.dev/media/store/assets/icons/gray/Close.svg" class="f" alt="Icon image">
                                <img src="https://rarefrostbites.pages.dev/media/store/assets/icons/white/Close.svg" class="hidden" alt="Icon image">
                            </button>
                            <button>
                                <img src="https://rarefrostbites.pages.dev/media/store/assets/icons/gray/Share.svg" class="f" alt="Icon image">
                                <img src="https://rarefrostbites.pages.dev/media/store/assets/icons/white/Share.svg" class="hidden" alt="Icon image">
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

the iframe is what I want to change the size based on the input tag and the .opt is where user controls it

Checking for vowels and consonants in a string and printing them out

I’m doing a challenge on Hackerrank, the task is to check for vowels and consonants in a string and printing both (ordered) in separate lines. I can print out the vowels just fine but can’t do the same with consonants. It won’t output them. Here’s my code:

    const vowels = 'aeiou'
    
    var consonants = []
    for (var i=0;i<s.length;i++) {
        if(vowels.includes(s[i])) {console.log(s[i])
        } 
        else {
            consonants+= s[i] + 'n'
        }
     
    } 
    
}

GAS have too many bugs with run scripts

I have many problems with run of scripts.
It sometimes skip some rows of code (that result of code unexpected)
If it skip it, it won`t call about error in run archive

GAS do it in any of my script ever.

That example of my code:

function onOpen() {

  var ui = SpreadsheetApp.getUi();  // Or DocumentApp or FormApp.

   ui.createMenu('Create new list from template')

      .addItem('template 1', 'menuItem1')

      .addItem('template 2', 'menuItem2')

      .addToUi();

}

function menuItem1() {
 var spreadsheet = SpreadsheetApp.getActive();
 spreadsheet.setActiveSheet(spreadsheet.getSheetByName('emplate 1'), true);
 spreadsheet.duplicateActiveSheet(); // it can skip it (script will brake my template list)
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets().length;
 spreadsheet.moveActiveSheet(sheet);
 spreadsheet.getActiveSheet().setName("yyyy-MM-dd "+(sheet)); // it can skip it (name won`t set)
 spreadsheet.setActiveSheet(spreadsheet.getSheetByName('template 1'), true);  // it can skip it (next code row will used on wrong list)
 spreadsheet.getActiveSheet().hideSheet(); // it can skip it (it won`t hided)
} 
...

I have an idea, that this trouble is appear of JS async working. I met that problem in another code and language with no promise system. It was a problem, that script don’t wait self previous row.
Its cool that JS is async, but I dont how it work in GAS.

there is In script GAS`s IDE “asyinc … await” schema instructed “unnecessary”.
Another my try:screen of message from GAS IDE

Please, help me to stabilize my scripts

Trying to read id_rsa

I am trying to read cat id_rsa, but is it throwing

cat: id_rsa: Permission denied

Also is not letting me push changes to the repository by saying

[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

What am i missing

check if url contains string and save value into cookie

I want to implement a referral system. For that I need to check page url, if it contains something like this: https://myurl.com/referralID=123

If the url does contain a referral then I need to save the ID value (123 in this example) into a cookie, which I will use later on (I will check if this cookie exists).

I’ve neither worked with cookies before, nor that experienced with React.

import React, { useEffect, Fragment } from "react"
import { Helmet } from "react-helmet"
import { useRuntime } from "vtex.render-runtime"
import "./style.global.css"

checkCookie() {
    let refId = window.location.href.indexOf('refferalID=123')

    if ( refId ) {
    // document.cookie = `refferalID=${value}`
        document.cookie = '123'
    }   
        else 
    {
        console.log("no refferal ID :(")
    }
}

const Head = ({}) => {
    return (
        <Fragment>
            <Helmet>                 
                {checkCookie() }
            </Helmet>
        </Fragment>
    )
}

Head.propTypes = {}

export default Head

How could I check url not only for refferalID=123, but for any ID and save this value into a cookie that could be sent afterwards?

Work around to access variable and functions within jQuery .ready() function?

Hi guys I need to test if a jquery script like the below one contains a given function (for example foo):

$( document ).ready( function() {
  let n = 5;
  function foo() {
    console.log(n * 2)
  }

  foo();
})

I tried this function to test whether is function or not:

function isFunction(x) {return Object.prototype.toString.call(x) === '[object Function]'}

but it didn’t because of the closure and eventually, I end up with a function not defined error.

Issue with Ajax and Jquery – response does not match with conditions

I have an issue with my code. For my studies, i need to make a simple form to connect with my database (mysql). I have to use ajax and jquery and i need to login with : admin and password : 1234.
I have already created this row in my database and now i’m try to show “I’m connected” or ” not connect” with AJAX.
But if i type anything in login & password, the result is always : “I’m connected”. I don’t see where is the problem, Could you help me to solve it please ?

here all codes

db.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
try{
$db = new PDO('mysql:host=xxxxx; dbname=xxxx','xxxx','xxxx');
}
catch(Exception $e){
echo "erreur de connexion".$e->getMessage();
}
?>

traitement.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('db.php');

$connexion = 'SELECT * FROM connexion WHERE login=:login AND motdepasse=:motdepasse';
$connexion = $db->prepare($connexion);
$connexion->bindParam(':login', $_POST['login']);
$connexion->bindParam(':motdepasse', $_POST['motdepasse']);

try {
$connexion->execute();
} catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$resultat = $connexion->fetch(PDO::FETCH_ASSOC);
var_dump($resultat);

index.html

    <!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- jquery cdn -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <title>Document</title>
</head>

<body>
    <div id="form">
        <fieldset>
            <legend>Formulaire de connexion</legend>
            <form action="#" method="POST">
                <label for="login">Login</label>
                <input type="text" id="login" name="login" required>
                <label for="motdepasse">Mot de passe</label>
                <input type="password" id="motdepasse" name="motdepasse" required>
                <button type="button" id="connexion">Me connecter</button>
            </form>
        </fieldset>
    </div>
    <div id="resultat"></div>
    <script src="script.js"></script>
</body>

</html>

script.js

    $(document).ready(function () {
    
$('#connexion').on('click',connexion);
});

function connexion(){
if(document.querySelector('form').checkValidity()){

    $.ajax({
        type: "POST",
        url: "traitement.php",
        data: "login="+$('#login').val()+"&motdepasse="+$('#motdepasse').val(),
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success: function(response) {
            if(response!=false){
                $('#resultat')
                .html('<span>Vous ĂȘtes maintenant connectĂ© !</span>')
                $('input').val('');
                console.log(response);
            }
            else{
                $('#resultat').html("Une erreur s'est produite");
                console.log('erreur');
            }
        }
    });
}
else{
    alert('Veuillez renseigner tous les champs');
}

};

getElementById not working when I try to pass a variable into the parameter


let id = 0;
const listings = document.querySelector(".results").querySelectorAll(".item");

listings.forEach((listing) => {

        // create the button HTML
        const button = document.createElement("button");
        button.setAttribute('id',`button${id}`);
        button.setAttribute('type', 'button');

        // testing button selection
        const test = document.getElementById(`button${id}`);
        console.log(test);

        // add the button to the specified div
        const div = listing.querySelector(".specific-div");
        div.appendChild(button);

        // increment id value
        id++;
    });

I am trying to add an onClick to the buttons that I create and thus I need to select them by ID. If I go to the JS console and type something like document.getElementById("button1") the console will return the correct button element. If I go into my code and change the variable to just a specific value, i.e

const test = document.getElementById("1");
console.log(test);

I also get the correct value returned. So the issue only arises when I do getElementById(some_variable). I tried using just the id without the template string and it does not work either. querySelector doesn’t work too, so I assume its a problem with the way I am implementing it not the method.

unable to extract a key value pair from an API response

{
   "config":{
      "adapter":[
         "Function xhrAdapter"
      ],
      "data":"{"phone":"9483275244","custId":"010000001"}",
      "env":{
         "FormData":null
      },
      "headers":{
         "Accept":"application/json, text/plain, */*",
         "Content-Type":"application/json"
      },
      "maxBodyLength":-1,
      "maxContentLength":-1,
      "method":"post",
      "timeout":0,
      "transformRequest":[
         [
            "Function transformRequest"
         ]
      ],
      "transformResponse":[
         [
            "Function transformResponse"
         ]
      ],
      "transitional":{
         "clarifyTimeoutError":false,
         "forcedJSONParsing":true,
         "silentJSONParsing":true
      },
      "url":"http://40.80.91.121:5001/api/Verifylogin",
      "validateStatus":[
         "Function validateStatus"
      ],
      "xsrfCookieName":"XSRF-TOKEN",
      "xsrfHeaderName":"X-XSRF-TOKEN"
   },
   "data":"{"result":"Success","message":"Success","payload":"[{"Name":"Raju K V","PhoneNo":"9483275244","Address":"S/o. Kuppaswamy Naidu Pritchard RoadOld SwarnakuppamGokul NilayamKGF - 563122.","Membership_no":"010000001","BranchCode":"BR001","BankCode":"BR001","RefId":"000025"}]"}",
   "headers":{
      "content-type":"text/plain; charset=utf-8",
      "date":"Wed, 06 Jul 2022 17:10:15 GMT",
      "server":"Kestrel",
      "transfer-encoding":"chunked"
   },
   "request":{
      "DONE":4,
      "HEADERS_RECEIVED":2,
      "LOADING":3,
      "OPENED":1,
      "UNSENT":0,
      "_aborted":false,
      "_cachedResponse":"undefined",
      "_hasError":false,
      "_headers":{
         "accept":"application/json, text/plain, */*",
         "content-type":"application/json"
      },
      "_incrementalEvents":false,
      "_lowerCaseResponseHeaders":{
         "content-type":"text/plain; charset=utf-8",
         "date":"Wed, 06 Jul 2022 17:10:15 GMT",
         "server":"Kestrel",
         "transfer-encoding":"chunked"
      },
      "_method":"POST",
      "_perfKey":"network_XMLHttpRequest_http://40.80.91.121:5001/api/Verifylogin",
      "_performanceLogger":{
         "_closed":false,
         "_extras":[
            "Object"
         ],
         "_pointExtras":[
            "Object"
         ],
         "_points":[
            "Object"
         ],
         "_timespans":[
            "Object"
         ]
      },
      "_requestId":null,
      "_response":"{"result":"Success","message":"Success","payload":"[{"Name":"Raju K V","PhoneNo":"9483275244","Address":"S/o. Kuppaswamy Naidu Pritchard RoadOld SwarnakuppamGokul NilayamKGF - 563122.","Membership_no":"010000001","BranchCode":"BR001","BankCode":"BR001","RefId":"000025"}]"}",
      "_responseType":"",
      "_sent":true,
      "_subscriptions":[
         
      ],
      "_timedOut":false,
      "_trackingName":"unknown",
      "_url":"http://40.80.91.121:5001/api/Verifylogin",
      "readyState":4,
      "responseHeaders":{
         "Content-Type":"text/plain; charset=utf-8",
         "Date":"Wed, 06 Jul 2022 17:10:15 GMT",
         "Server":"Kestrel",
         "Transfer-Encoding":"chunked"
      },
      "responseURL":"http://40.80.91.121:5001/api/Verifylogin",
      "status":200,
      "timeout":0,
      "upload":{
         
      },
      "withCredentials":true
   },
   "status":200,
   "statusText":"undefined"
}

Im getting this response from an API, here I wanna extract the RefId present in data and inside data in that payload, refId is present. How can I console log that value? I’ve tried response.data it gave the data correctly as it is here, but when i try console.log(response.data.result ); i get undefined. Why is that so?

My Api code

 Axios.post("url",{
            
            phone:props.usermobilenumber,
            custId:props.custid
        }).then((resp)=>{
            console.log(resp.data);
            // ToastAndroid.show(resp.payload.RefId)
        })

Please help me how can i extract the RefId

Javascript string modifications with replace(), join(), split() and regex [duplicate]

I am looking for help to reconstruct the following strings : rawIdColumn into Raw Id and the same for startDateColumn into Start Date.

The idea is to remove the Column word, capitalize the first letter and add a space between the 2 words.

My progress so far :

word1 = rawIdColumn

word2 = startDateColumn

word1.replace("Column", "").split(/[A-Z]/g).join(" ") ---> Output = raw d

word2.replace("Column", "").split(/[A-Z]/g).join(" ") ---> Output = start ate

Split is removing the capital letter from the second word , but I want to keep it.