Update useState value with useEffect with a simple example, React

I’ve seen this question being asked countless times, and just like others, I can’t spot an answer that makes me understand how you can work with it to solve the fact useState is an async function and will save its value until a new one is set, I’ve seen answers with useEffect, but I can’t get a correct notion of how you can use it to update the useState value, I’d really appreciate if some good Samaritan programmer could give me a very simple example of useState holding the value until it’s updated and how useEffect could update it instantly, so I can understand and implement that logic to my code, I also think this would help others like me.

jQuery append in vanilla js

I am trying to add html code from data-prototype:

<div id="accordion" class="js-collection" data-prototype="<div class=&quot;card answer-section&quot; id=&quot;__name__&quot;>
        <div class=&quot;card-header&quot; id=&quot;heading__name__&quot;>...</div></div>
<script>console.log('hi');">
</div>

As you can see, there is also some js code.

When I try to add it with jquery:

let el = document.querySelector('#accordion');
let template = el.dataset.prototype;
let $root = $(el);

$root.append(template);

Everything works fine, I mean javascript code is executing.

But when I try to do it with vanilla js:

let el = document.querySelector('#accordion');
let template = el.dataset.prototype;
let wrapper = document.createElement('div');

wrapper.innerHTML = template;
el.insertBefore(wrapper.firstElementChild, document.getElementById('btn1'));

The js code is not executing.

How can I make the same functionality as jQuery append() function in vanilla JS?
I have tried to analyze jquery code, but I cannot understand it

how to run cronjob at last day of each month node.js

I have this:

    app.get('/createThePayment', async (req, res) => {
    
    let month = new Date();
    month = 1
    if (month == 0) {
        month = 12
    }
    createPaymentIntentTwo(req, res, month)

})

but what I want to do is actually run this:

let month = new Date();
    month = 1
    if (month == 0) {
        month = 12
    }
    createPaymentIntentTwo(req, res, month)

at every last day of the month, but I cant seem to figure it out with cronjob.

var PaymentCron = new CronJob('0 0 0 * * *', function() {

something in this format?

Component mounted twice on page refresh when using localstorage for Auth0

For some reason, when using cacheLocation=’localstorage’ for Auth0, a page refresh in our app is causing a call to happen twice…

enter image description here
Without localstorage it works fine…

enter image description here

We’re using localstorage when running Cypress tests as the page redirect at login doesn’t work without it.

The duplication does not happen when first logging in, just on subsequent page refreshes when logged in. Removing the comment in the below code duplicates the call as in the first screenshot…

return (
    <Auth0Provider
        domain={process.env...}
        clientId={process.env...}
        redirectUri={
            typeof window !== 'undefined' ? window.location.origin : `http://localhost:3000`
        }
        onRedirectCallback={onRedirectCallback}
        audience={process.env...}
        //cacheLocation='localstorage'
    >
        <UserInfoProvider>
            <PubSubProvider>
                <StackedLayout>
                    <Component {...pageProps} />
                </StackedLayout>
            </PubSubProvider>
        </UserInfoProvider>
    </Auth0Provider>
)

Fetch vs ajax vs XMLHttpRequest why is Fetch so much more incredibly fast?

Okay so these last couple of days i have been optimizing a client table.

There are a lot of clients 10k+ and obviously the table took ages to load.
Front-end team did the pagination + filters + reordering and i was wanting to keep it that way.

So i started by trying to inject rendered HTML via AJAX, which obviously sucked. was acceptably fast, but gigantic memory hog, table was very slow after.

So after that, i tried loading the data in via AJAX in JSON format and appending to the table with javascript.

I tried multiple methods of doing this, the best one was 500-1000 clients at a time, but it took more than 30 seconds to complete the table, and the page in the meantime was slow.

I soldiered on, and managed to shave off some seconds on the backend, but still, if i simply loaded the API on the browser the results appeared instantly and didn’t take 10+s per call.

This is when i tried XMLHttpRequest which yielded more or less the same resutls. And then i found out fetch, which is amazing. with fetch it now takes under 3 seconds to fully load the table.

So my question is, why? yes i could probably find out why if i deep dive the docs, but i simply am very busy and super curious, surely someone already knows this.

PS if anyone is curious on the code i am using:

Best solution (fetch)

for (var jj of {{ ret|safe }}) {
          fetch("/clients/table/build1/?start="+String(jj)).then(function (response) {
              response.json().then(function (request) {
                  for (let i = 0; i < request['results'].length; i++) {
                  $("#myAllClient_1").DataTable().row.add(<<CLIENT DATA>>)
                  }
            $("#myAllClient_1").DataTable().draw(false);
            <<bit more code>>

slow ajax code:

$.ajax({
          method: "GET",
          dataType: "JSON",
          url: "/clients/table/build1/?start=" + snum,
          success: function (data) {
              for (let i = 0; i < data['results'].length; i++) {
                  $("#myAllClient_1").DataTable().row.add(<<CLIENT DATA>>);
              }
              $("#myAllClient_1").DataTable().draw(false);
              <<bit more code>>
      })

radio buttons with simple input

dear stackoverflow!

Professionals, please help.

i need to implement a form like this in Django:

enter image description here

If a user enters something in the “another amount” field, the radio buttons become disabled.

I really have no idea.

my html:

                        <div class="payment__amount">
                            <div class="payment__amount__1">
                                <div class="form-check payment__amount__check">
                                    {{ form.amount_select.0 }}
                                </div>
                                <div class="form-check payment__amount__check">
                                    {{ form.amount_select.1 }}
                                </div>
                            </div>
                            <div class="payment__amount__2">
                                <div class="form-check payment__amount__check">
                                    {{ form.amount_select.2 }}
                                </div>
                                <div class="form-check payment__amount__check">
                                    {{ form.amount_select.3 }}
                                </div>
                            </div>
                        </div>
                        {{ form.amount_input }}

my forms.py

CHOISES = [
    ('50', '50'),
    ('100', '100'),
    ('200', '200'),
    ('500', '500')
]


class CheckoutForm(forms.Form):
    amount_select = forms.IntegerField(widget=forms.RadioSelect(choices=CHOISES))
    amount_input = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': "another amount"}))

Thank you very much!

How to make open 2 link or more pages when clicked

How to make open 2 link or more pages when clicked in html and java

html

<td style="background-color:#EE9933;">
<input type="button" id="logtkt" value="Item Logs tkt" class="button" style="Color:blue;width:170px;position: relative;Top: 1px;Left: 1px" onclick="logtkt()"/>
</td>

js

 function tktNum() {
 var str = document.getElementById('tktTree').value;var t;var res = str.substr(1, 10);
 if (str.substr(0,1) == 0) {t = res;} else {t = str;} tktTree.value = t;}


    function logtkt(){
    var  t = document.getElementById('tktTree').value;
    parent.open("http://-----="+t+"");}

How to set state within a reducer

I have an array of product objects inside my reducer and I have an empty array of brand as well. I want to add all the unique brands from my products object array into my brands array in my reducer, is there any way I can do that?

My Reducer:

import * as actionTypes from './shop-types';

 const INITIAL_STATE = {
 products: [
{
  id: 1,
  brand:"DNMX"
},
{
  id: 2,
  brand: "Aeropostale",
},
{
  id: 3,
  brand: "AJIO",
},
{
  id: 4,
  brand: "Nike",
},
],
  cart: [],
  brands: [], //<---- I want to add all the unique brands inside this array
  currentProduct: null,
};

  const shopReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
  case actionTypes.ADD_TO_CART:
  const product = state.products.find(
    (product) => product.id === action.payload.id
  );
  if (product !== null) {
    return {
      ...state,
      cart: state.cart.concat(product),
    };
  } else {
    return null;
  }
default:
  return state;
 }
 };

export default shopReducer;

how does the javascript interpreter work in classes

I have this js code , when it executes “user clicked” effectively gets printed but an error is thrown when trying to execute funA:

app.js:13 Uncaught TypeError: this.funA is not a function
at HTMLBodyElement.handleclick (app.js:13:14)

I guess the interpreter hasn’t read the funA function yet at the time of executing handleclick? What happens here and how could I solve this.

class UI {
    constructor() {
        this.body = document.querySelector("body")
        this.body.onclick = this.handleclick
    }

    funA() {
        console.log("called funA")
    }

    handleclick(e) {
        console.log("user clicked")
        this.funA()
    }
}


new UI()

What pattern should I use in a React form that needs an item ID when submitting?

I have a web app that requires some crud functionality. In this specific case, the user needs to update an existing item in a database. Right now I have a form component that I tried to keep as “dumb” as possible, however, now I am not so sure if it is as “dumb” as it could be while still sticking to good React patterns.

I am passing in 3 props to my form:

  1. Existing values which I then set in state as the inputs are controlled
  2. ID of the item that user is updating
  3. Function called “onSubmit” which is essentially an API call to my database. It requires updated values and an ID as arguments

On form submit, I call my “onSubmit” function that has been passed in via props, which takes in the ID I have also passed in via props as well as the new values the user has selected via the inputs on the form.

Is this the common pattern to use in this situation?

Iterating through and object property and putting the values inside variables in javascript

I’m trying to iterate through an object using the for...in loop to get the values of all its properties and put them inside variables. I’m stumbling on this.

What I would like to do is loop through the object properties, put the value inside a variable of the same the name as the property to use on them on another variable


somePromise.then(response => {  

  for (let property in response) {
    property = response[property]  // this doesn't work cause reuses the same variable
  }

  /// I take the value of each property from the loop and pass it down 
  user.updateInfoFromOldDB(
    userID,
    nguid,
    property1 
    property2,
    property3
    property4,
  )

  ...ommited_code
})

Can a badly configured nginx reverse proxy or cloudflare cdn causes my api to be called twice on one request

Problem:
I recently uploaded my website to my linode server to be able to use it with a domain and enable https. Everything looked liked it was working fine on my express.js api, but I recently checked my requests log and each time I made a request to domain.com/api/count it was printing two requests. The same goes for every other calls I made. Locally it works fine, but on my server it is not. So my questions is, is it possible that a misconfigured nginx reverse proxy or the cloudflare cdn causes that. I cannot find any other reason why it would since locally it works. Any help would be appreciated, thanks you!

If you need my nginx config or any other information, feel free to ask me.