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>>
      })

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.

How to Upload Images to Firebase Storage and Retrieve Image URL’s When Using Dropzone in React.js

I have a <Dropzone/> component in my react website that allows my users to upload multiple images just by either clicking or dragging and dropping.

When I upload the images they are being saved in my firebase storage but the URL’s for each indiviual image are not being set and i get a firebase error that reads:

"Uncaught (in promise) FirebaseError: Firebase Storage: Object 'propertyImages/Picture1.png+4b80d-6dd0-4b40-cadc-8e7845677bbd' does not exist. (storage/object-not-found)
{
  "error": {
    "code": 404,
    "message": "Not Found."
  }
}"

I don’t know why it isn’t setting the url for each image, i believe it is because it is overwritting the previous download urls. How can i make Dropzone work properly?

What am I doing wrong?

Here is my code:

  import Dropzone, {useDropzone} from "react-dropzone"

  const [urls,setUrls] = useState([]);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDropAccepted: onFilesDrop, maxFiles: 5 });




  function onFilesDrop(files) {
    files.map((item, index) => {
        let uploadTask = storage.ref(`propertyImages/${item.name}+${uuid()}`).put(item);
        uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
            setUrls(prevState => {
                return [...prevState, downloadURL]
            })
        })
    })
}
return (
  <CardTitle className="mb-3 h4">Property Images (MAX IMAGES 5)</CardTitle>
                    <div className="dropzone" >
                    <Dropzone
                        onDrop={acceptedFiles =>
                          onFilesDrop(acceptedFiles)
                        }
                      >
                        {({ getRootProps, getInputProps }) => (
                          <div>
                            <div
                              className="dz-message needsclick"
                              {...getRootProps()}
                            >
                              <input {...getInputProps()} />
                              <div className="dz-message needsclick">
                                <div className="mb-3">
                                  <i className="display-4 text-muted bx bxs-cloud-upload" />
                                </div>
                                <h4>Drop files here or click to upload.</h4>
                              </div>
                            </div>
                          </div>
                        )}
                      </Dropzone>
                      
)

Quick sort turns array into string [duplicate]

i have made an quick sort algorithm, but it returns a string instead of an wanted array.

const quickSort = (arr) =>  {
  if (arr.length < 2) {
    return arr;
  } else {
    let pivot = arr[0]

    let less = arr.slice(1).filter(i => i <= pivot)
    let grater = arr.slice(1).filter(i => i > pivot)

    return quickSort(less) + [pivot] + quickSort(grater);
  }
}

console.log(quickSort([1, 5, 93, 2]));

I can’t figure out why, my guess it that is has some thing to do with the line:

return quickSort(less) + [pivot] + quickSort(grater);

XHR Interceptor in Typescript

Why is the following monkey patch not allowed in Typescript?

const oldXHROpen = window.XMLHttpRequest.prototype.open

window.XMLHttpRequest.prototype.open = function (
    method: string,
    url: string,
    ...args: any[]
): void {
    return oldXHROpen.apply(this, [method, url, ...args])
}

It gives the following error:

Argument of type '[string, string, ...any[]]' is not assignable to parameter of type '[method: string, url: string | URL, async: boolean, username?: string | null | undefined, password?: string | null | undefined]'.
  Target requires 3 element(s) but source may have fewer.

However when looking at the definitions of open there is a method which only requires two arguments.

open(method: string, url: string | URL): void;

How can I make an SVG segment clickable in a webpage?

Below is a code snippet I am using to draw a simple square (though the shape will get much more complex further in the project as it is meant to visualize DWG files imported from a back-end).

I have however hit a wall in trying to get the SVG segment that is clicked.
What I am looking to do in the current setup is:

  1. User clicks on a segment of the SVG
  2. The segment closest to it (with some margin) is captured
  3. I can use that captured information in my code (preferably 4 number values, representing the x1, x2, y1 and y2)

The problem I am having is that I don’t know how to identify the segments, while I can see that they advance with an [x1, y1, x2, y2, x3, y3, x4, y4] pattern.

var draw = svg.SVG().addTo('body').size(300, 300);
var arr = new svg.Array([0, 0, 0, 100, 100, 100, 100, 0])
draw.polygon(arr).fill("0x000000");

An example of what I want to be able to do:

get the line along the point [50, 0] which should be in the first segment of the shape drawn in the snippet above. I need to correctly identify the segment the user has selected so I can work with that information. If I can somehow get the begin and end coordinate of the segment that was clicked that would probably lead me to a successful solution.

Acess violation for an East project

Ok, so I have a east project and you need to get past something were calling a “blue screen” and it says;

System error:access violation in 0x070cbf32 for provided URL

The access level for the URL is restricted pending usage of correct phrase key. Please use a different phrase key or see administrator for assistance. Provided phrase key should be in alphabetic characters only.

Error message 0x070cbf32; explicit violation found. There is a picture provided. https://i.stack.imgur.com/YvWhe.png