Issue in calling a 3rd party API via Axios in React JS

Problem Statement:- i wanted to have a respective post-office dropdown for the user entered pincode. In this way, i have used below mentioned api to call with axios. I got the required post office details in the dropdown but the problem is that the fetching of data never stops, i keep getting the extracted data from API continuously and it never stops until I close the server. Below is my mentioned code.

import React, { useState } from 'react'
import axios from "axios"

export default function Test() {
    const [inputValue, setInputValue] = React.useState("");
    const [districtName, setDistrictName] = React.useState("");
    const [stateName, setStateName] = React.useState("");
    const [dataArray, setDataArray] = React.useState("")
    const onChangeHandler = event => {
        setInputValue(event.target.value);
    };

    if (inputValue.length === 6) {
        console.log(inputValue)
        axios.get("https://api.postalpincode.in/pincode/" + inputValue).then(res => {
            var data = res.data;
            console.log("data: ", JSON.stringify(data))
            setDistrictName(data[0].PostOffice[0].District)
            setStateName(data[0].PostOffice[0].State)
            console.log("data_1: ", districtName + " " + stateName)
            var items = []
            data[0].PostOffice.forEach(element => {
                items.push(<option value={element.Name}>{element.Name}</option>)
                
            });
            setDataArray(items);
            console.log("items:",items);
        })
    }

    return (
        <div>
            <div>
                <label type="text" name="pincode">Pincode</label>
                <input
                    type="text"
                    name="pincode"
                    onChange={onChangeHandler}
                    value={inputValue}
                />
            </div>

            <div>

                <label type="text" name="district">District</label>
                <input
                    type="text"
                    name="district"
                    value={districtName}

                />
            </div>

            <div>
                <label type="text" name="state">State</label>
                <input
                    type="text"
                    name="state"
                    value={stateName}
                />
            </div>

            
                <select>
                    {dataArray}
                </select>

        </div>
    )
}

How can I use a parameter to change HTML text?

I’m using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:

<!DOCTYPE html>
<html>
    
    <head>
        <script type="text/javascript" 
            src="shoepoo.js">
        </script>
    </head>
    <body>
      
        <div>
            <p id="text" style="color:purple; 
                font-weight:bold;font-size:20px;">
            </p>
            <script type="text/javascript"> shoeName(); </script>
        </div>

    </body>
</html>

const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();

//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array 
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
    
    products.forEach(
        function names (product) {
            document.getElementById("text").innerHTML = product.shoeName;
    })
    
});
};

Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it’s a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?

Filter date time with substring and date object

I have this string 2022-02-25 06:09 AM. How do I use return just 06:09 AM (without seconds)?

I tried two ways. One way is to convert the string into Date object and then use toLocaleTimeString. But the output is 6:09:00 AM which includes the second. Here is my code.

getMyTime(lastUpdate) { 
    let d = new Date(lastUpdate);
    return d.toLocaleTimeString();
},

  

The other way is I used substring which returns 25 06:09 AM. Not sure why it get 25. Here is my code.

getMyTime(lastUpdate) { 
    return lastUpdate.substring(19,8);        
},

How to submit files to MVC Action using FormData

I am creating an ASP.NET Core 6 file upload application. This is my code:

FORM

<form asp-controller="Home" asp-action="UploadFiles" method="post" enctype="multipart/form-data" id="uploadForm">
    <input type="file" class="form-control-file" multiple name="files">
    @foreach (var folder in @Model.Folders)
    {
        <input id="filePathUrl" type="radio" asp-for="Folders" value="@folder" />
        @folder
    }
<button type="submit" class="btn custom-button">Upload Files</button>

jQuery

    function processFiles(confirmOverwrite = false){
    const filePath = $("#filePathUrl").val();
    const fileList = $(".form-control-file")[0].files;
    const files = Array.from(fileList);

    let formData = new FormData();
    files.forEach(file => formData.append("files[]", file));

    const URL = '@Url.Action("UploadFiles", "Home")';

    $.ajax({
        url: URL + '?folders=' + filePath + '&confirmOverwrite=' + confirmOverwrite,
        type: 'post',
        data: formData,
        // dataType: 'json',
        contentType: false,
        processData: false,
              ...

MVC Action

       [HttpPost]
    public async Task<JsonResult> UploadFiles(IEnumerable<IFormFile> files, string folders, bool confirmOverwrite = false)
    {
        List<string> existingFiles = new();
        var filesToBeSaved = new List<(IFormFile file, string filePath)>();
        
        foreach (var file in files)
        {
            string trimmedFileName = file.FileName.Replace(" ", "");
            var filePath = Path.Combine(folders, trimmedFileName);

            if (System.IO.File.Exists(filePath) && !confirmOverwrite)
            {
                existingFiles.Add(file.FileName + "(" + trimmedFileName + ")");
            }
            else
            {
                filesToBeSaved.Add((file, filePath));
            }
        }
       ...

I have removed alot of code to keep things relevant and simple.

Why is files argument appearing as null when I submit the form??

Sorting Algorithm Visualizer Trouble

I’m really struggling with this application. I will be putting the code below this section. However, I am trying to visualize the sorting actually taking place. I have the draw function, which actually iterates over the array it is given and draws the lines in the correct place. I’m struggling to find out if I should call the draw() function within the separate algorithms(bubble, merge, quick, so on), or if there is a way to adjust the draw() function to properly draw each line and have a setTimeout() function on it so you can watch it sort through the array. Comment if you need more information, I’m always willing to provide more if need be.

//Sets Variables Up for Canvas and Canvas Context(ctx)
let canvas = document.querySelector("#sortCanvas");
let ctx = canvas.getContext("2d");
//Sets Variable sortingArray to be an Array
let sortingArray = [];
//Adding an event listener to #resetButton in HTML
let resetButton = document.querySelector("#resetButton").addEventListener("click", function reset() {
  //Clears Canvas and Re-Runs through LineDraw Function
  drawRect(0, 0, canvas.width, canvas.height, "blue");
  lineDraw();
});
  
//Grabs random integer between 1 and the Height of the Canvas
function getRndmInt() {
  return Math.floor(Math.random() * canvas.height);
}
//This function is called in Bubble Sort function and swaps two values
function swap(arr, x, y) {
  let temp = arr[x];
  arr[x] = arr[y];
  arr[y] = temp;
}
//Bubble Sorting Algorithm
function bubbleSort() {
  for(i = 0; i < sortingArray.length; i++) {
    for(j = 0; j < sortingArray.length-i-1; j++) {
      let a = sortingArray[j];
      let b = sortingArray[j + 1];
      if(a > b) {
        swap(sortingArray, j, j + 1);
        setTimeout(function() {}, 10)
      }
    }
  }
}
/*
var container = document.getElementById("array");

// Function to generate the array of blocks
function generatearray() {
    for (var i = 0; i < 20; i++) {

        // Return a value from 1 to 100 (both inclusive)
        var value = Math.ceil(Math.random() * 100);

        // Creating element div
        var array_ele = document.createElement("div");

        // Adding class 'block' to div
        array_ele.classList.add("block");

        // Adding style to div
        array_ele.style.height = `${value * 3}px`;
        array_ele.style.transform = `translate(${i * 30}px)`;

        // Creating label element for displaying
        // size of particular block
        var array_ele_label = document.createElement("label");
        array_ele_label.classList.add("block_id");
        array_ele_label.innerText = value;

        // Appending created elements to index.html
        array_ele.appendChild(array_ele_label);
        container.appendChild(array_ele);
    }
}

// Promise to swap two blocks
function swap(el1, el2) {
    return new Promise((resolve) => {

        // For exchanging styles of two blocks
        var temp = el1.style.transform;
        el1.style.transform = el2.style.transform;
        el2.style.transform = temp;

        window.requestAnimationFrame(function() {

            // For waiting for .25 sec
            setTimeout(() => {
                container.insertBefore(el2, el1);
                resolve();
            }, 250);
        });
    });
}

// Asynchronous BubbleSort function
async function BubbleSort(delay = 100) {
    var blocks = document.querySelectorAll(".block");

    // BubbleSort Algorithm
    for (var i = 0; i < blocks.length; i += 1) {
        for (var j = 0; j < blocks.length - i - 1; j += 1) {

            // To change background-color of the
            // blocks to be compared
            blocks[j].style.backgroundColor = "#FF4949";
            blocks[j + 1].style.backgroundColor = "#FF4949";

            // To wait for .1 sec
            await new Promise((resolve) =>
                setTimeout(() => {
                    resolve();
                }, delay)
            );

            console.log("run");
            var value1 = Number(blocks[j].childNodes[0].innerHTML);
            var value2 = Number(blocks[j + 1]
                        .childNodes[0].innerHTML);

            // To compare value of two blocks
            if (value1 > value2) {
                await swap(blocks[j], blocks[j + 1]);
                blocks = document.querySelectorAll(".block");
            }

            // Changing the color to the previous one
            blocks[j].style.backgroundColor = "#6b5b95";
            blocks[j + 1].style.backgroundColor = "#6b5b95";
        }

        //changing the color of greatest element
        //found in the above traversal
        blocks[blocks.length - i - 1]
                .style.backgroundColor = "#13CE66";
    }
}

// Calling generatearray function
generatearray();

// Calling BubbleSort function
BubbleSort();
*/

//Insertion Sort Algorithm
function insertSort() {
  for(i = 0; i < sortingArray.length; i++) {
    key = sortingArray[i]
    
    j = i-1
    
    while(j >= 0 && key < sortingArray[j]) {
      sortingArray[j +1] = sortingArray[j];
      j-= 1
    }
    sortingArray[j + 1] = key
  }
}

//Quick Sort Algorithm
function quickSort(arr, low, high) {
  //Partition Function assigns pivot variable to be the higher value of array assigned within parameters
  function partition(arr, low, high) {
    let i = (low - 1);
    let pivot = arr[high];
    for(j = low; j < high; j++) {
      if (arr[j] <= pivot) {
        i = i + 1
        let temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
      }
    }
    let temp2 = arr[i+1]
    arr[i+1] = arr[high]
    arr[high] = temp2
      
    return (i + 1)
  }
  
  if(low < high) {
    p = partition(arr, low, high);
    
    quickSort(arr, low, p - 1);
    quickSort(arr, p + 1, high);
  }
}

function heapSort(arr) {
  function heapify(arr, n, i) {
    let largest = i;
    let l = 2 * i + 1;
    let r = 2 * i + 2;
    
    if(l < n && arr[largest] < arr[l]) {
      largest = l;
    }
  
    if(r < n && arr[largest] < arr[r]) {
      largest = r;
    }
  
    if(largest != i) {
      temp = arr[i];
    
      arr[i] = arr[largest];
      arr[largest] = temp;
      
      heapify(arr, n, largest);
    }
    
    return arr
  }

  let n = arr.length;
  let i = Math.floor(n / 2 - 1);
  let k = n - 1
  
  
  while(i >= 0) {
    heapify(arr, n, i)
    i--
  }
  
  while(k >= 0) {
    temp = arr[0];
    
    arr[0] = arr[k];
    arr[k] = temp;
    
    heapify(arr, k, 0);
    
    k--
  }
  
  return arr
}

function mergeSort(arr) {
  if(arr.length > 1) {
    let mid = Math.ceil(arr.length / 2);
    let l = arr.splice(0, mid);
    let r = arr.splice(-mid);
    
    mergeSort(l);
    mergeSort(r);
    
    i = 0
    j = 0
    k = 0
    
    while(i < l.length && j < r.length) {
      if(l[i] < r[j]) {
        arr[k] = l[i];
        i++
      } else {
        arr[k] = r[j];
        j++
      }
      k++
    }
    
    while(i < l.length) {
      arr[k] = l[i];
      i++
      k++
    }
    
    while(j < r.length) {
      arr[k] = r[j];
      j++
      k++
    }
  }
}

function iteration() {

}

//Draws all of the lines and prompts the user what type of sorting they would like to take place.
function lineDraw() {
  //Draw function assigns line drawing to a single function
  function draw(x, y, a, b, color, lineWid) {
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWid;
    
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(a, b);
    ctx.stroke();
  }
  //Assigns a random integer to sortingArray at index i
  for(i = 0; i < canvas.width; i++) {
    sortingArray[i] = getRndmInt();
  }
  //Assigns sorting choice to be the answer to the window prompt
  let sortingChoice = window.prompt("What sorting algorithm would you like to see? (Bubble, Insertion, Quick, Heap, and Merge)");
  //Checks to see what sorting choice is decided via sortingChoice
  //Bubble Sort Choice
  if(sortingChoice === "bubble sort" || sortingChoice === "Bubble Sort" || sortingChoice === "bubble" || sortingChoice === "Bubble") {
    bubbleSort();
  //Insertion Sort Choice
  } else if(sortingChoice === "insertion sort" || sortingChoice === "Insertion Sort" || sortingChoice === "insertion" || sortingChoice === "Insertion") {
    insertSort();
  //Quick Sort Choice
  } else if(sortingChoice === "quick sort" || sortingChoice === "Quick Sort" || sortingChoice === "quick" || sortingChoice === "Quick") {
    quickSort(sortingArray, 0, sortingArray.length-1);
  //Heap Sort Choice
  } else if(sortingChoice === "heap sort" || sortingChoice === "Heap Sort" || sortingChoice === "heap" || sortingChoice === "Heap") {
    heapSort(sortingArray);
  //Merge Sort Choice
  } else if(sortingChoice === "merge sort" || sortingChoice === "Merge Sort" || sortingChoice === "merge" || sortingChoice === "Merge") {
    mergeSort(sortingArray);
  //Not A Valid Option Alert
  } else {
    alert("That is not a valid option! Please try again!")
    lineDraw();
  }

  for(i = 0; i < sortingArray.length; i++) {
    for(j = 0; j < sortingArray.length; j++){
      if(j > j + 1) {
        swap(sortingArray, j, j + 1)
        setTimeout(function(){}, 10)
      }
    }
  }

  //Actually draws lines sortingArray.length times
  for(i = 0; i < sortingArray.length; i++) {
    draw(i, canvas.height, i, canvas.height - sortingArray[i], "white", 2);
  }
}
//Draw rectangle where sorting takes place
function drawRect(x, y, width, height, color) {
  ctx.beginPath();
  ctx.rect(x, y, width, height);
  ctx.fillStyle = color;
  ctx.fill();
}
//Calls the initial drawRect and lineDraw functions
drawRect(0, 0, canvas.width, canvas.height, "blue");
lineDraw();

how to defferentiat asyn by given example? [duplicate]

**
Why same code but different output
**
**
In the below code i have given two exaple with litle changes but the output of code is very different.
Why javascrript give the differ output.
Please explain why so?
**

function asyncFun() {
    for (let counter=0; counter < 10; counter++) {
        setTimeout(() => {
            console.log(counter);
        }, 100);
    }
}
asyncFun();
//output
0
1
2
3
4
5
6
7
8
9

function asyncFun() {
   
    for (var counter=0; counter < 10; counter++) {
        setTimeout(() => {
            console.log(counter);
        }, 100);
    }
}
asyncFun();

//output
10
10
10
10
10
10
10
10
10
10

Enable proprietary codec in Electron js

I want to use proprietary codec in electron js because I am making a client for jellyfin but I was not able to find a proper solution, i looked into using mpv.js but that seems to be abandoned. I don’t have issues with build my own electron build.

Can’t perform a React state update on an unmounted component on class type

Problem
I am writing an application in React and was unable to avoid a super common pitfall, which is calling setState(…) after componentWillUnmount(…).

I looked very carefully at my code and tried to put some guarding clauses in place, but the problem persisted and I am still observing the warning.

Therefore, I’ve got two questions:

How do I figure out from the stack trace, which particular component and event handler or lifecycle hook is responsible for the rule violation?
Well, how to fix the problem itself, because my code was written with this pitfall in mind and is already trying to prevent it, but some underlying component’s still generating the warning.

enter image description here

Code

import React, { Component } from "react";
import "./2048Game.css";
import Grid from "./Grid";
import NumberTable from "./NumberTable";
import Score from "./Score";
import Hover from "./Hover";

class Puzzle extends Component {
  _isMounted = false;
  constructor(props) {
    super(props);

    this.state = {
      grid: new Grid(),
      best: 0,
      beginX: 0,
      beginY: 0,
      endX: 0,
      endY: 0,
      enableSwipe: false,
    };
  }

  static getPosDuringEvent(e) {
    let X, Y;
    if (e.touches) {
      X = e.touches[0].screenX;
      Y = e.touches[0].screenY;
    } else {
      X = e.screenX;
      Y = e.screenY;
    }
    return [X, Y];
  }

  // 컴포넌트가 생성되고 render 호출 후, 최초 한번
  componentDidMount() {
    let events = {
      keydown: this.onKeyPressed,
      touchstart: this.onTouchStart,
      mousedown: this.onTouchStart,
      touchmove: this.onTouchMove,
      touchend: this.onTouchEnd,
      mousemove: this.onTouchMove,
      mouseup: this.onTouchEnd,
      gesturestart: this.onGestureStart,
    };

    this._isMounted = true;

    for (let e in events) {
      document.addEventListener(e, events[e].bind(this));
      break;
    }
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  onKeyPressed(e) {
    let legalKey = false;
    let grid = this.state.grid;
    const actionMap = { 37: "left", 38: "up", 39: "right", 40: "down" };
    if (e.keyCode >= 37 && e.keyCode <= 40) {
      let action = actionMap[e.keyCode];
      legalKey = grid.action(action);
    }
    if (legalKey) {
      grid.addValue();
    }
    this.setState({ grid: grid });
    this.updateBest();
    e.preventDefault();
  }

  onTouchStart(e) {
    let [X, Y] = Puzzle.getPosDuringEvent(e);
    this.setState({
      beginX: X,
      beginY: Y,
      endX: X,
      endY: Y,
      enableSwipe: true,
    });
    e.preventDefault();
  }

  onTouchMove(e) {
    let [X, Y] = Puzzle.getPosDuringEvent(e);
    this.setState({ endX: X, endY: Y });
    e.preventDefault();
  }

  onTouchEnd(e) {
    let grid = this.state.grid;
    let [beginX, beginY] = [this.state.beginX, this.state.beginY];
    let [endX, endY] = [this.state.endX, this.state.endY];
    if (
      Math.pow(endX - beginX, 2) + Math.pow(endY - beginY, 2) > 10 &&
      this.state.enableSwipe
    ) {
      let action = "";
      if (Math.abs(beginX - endX) > Math.abs(beginY - endY)) {
        action = beginX < endX ? "right" : "left";
      } else {
        action = beginY < endY ? "down" : "up";
      }
      if (grid.action(action)) {
        grid.addValue();
      }
    }
    this.setState({ grid: grid, enableSwipe: false });
    this.updateBest();
    e.preventDefault();
  }

  onGestureStart(e) {
    this.setState({ enableSwipe: false });
    e.preventDefault();
  }

  restart() {
    this.setState({ grid: new Grid() });
  }

  updateBest() {
    if (this.state.grid.score > this.state.best) {
      this.setState({ best: this.state.grid.score });
    }
  }

  render() {
    return (
      <div>
        <div id={"score-group"}>
          <Score info={"SCORE"} score={this.state.grid.score} />
          <Score info={"BEST"} score={this.state.best} />
        </div>
        <NumberTable numbers={this.state.grid.numbers} />
        <Hover
          alive={this.state.grid.alive()}
          restart={this.restart.bind(this)}
        />
      </div>
    );
  }
}

export default Puzzle;

I also used _isMounted. Is there anyone who can convert these codes in class type into function types?
Then I can useEffect(), but I can’t change it. Help me.

Drag-n-Copy Data from one div to the next?

Hoping to get some help on drag and copy operation from one contenteditable div to the next. Similar to how you can drag and copy in a spreadsheet. The user should be able to enter some data in the divs and drag and copy it to other div elements.

Got a lot of help on this code from Nippey at this link (but it’s not exactly what I need). HTML5 drag and copy?

Would appreciate any help :).


<!DOCTYPE html>
<html>
  <head>
    <style>
      #div1,
      #div2,  
      #div3 {
        float: left;
        width: 100px;
        height: 35px;
        margin: 10px;
        padding: 10px;
        border: 1px solid black;
        cursor: pointer;
      }
    </style>
    <script>
      function allowDrop(ev) {
        /* The default handling is to not allow dropping elements. */
        /* Here we allow it by preventing the default behaviour. */
        ev.preventDefault();
      }

      function drag(ev) {
        /* Here is specified what should be dragged. */
        /* This data will be dropped at the place where the mouse button is released */
        /* Here, we want to drag the element itself, so we set it's ID. */
        ev.dataTransfer.setData('text/html', ev.target.id);
      }

      function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData('text/html');
        /* If you use DOM manipulation functions, their default behaviour it not to 
       copy but to alter and move elements. By appending a ".cloneNode(true)", 
       you will not move the original element, but create a copy. */
        var nodeCopy = document.getElementById(data).cloneNode(true);
        nodeCopy.id = 'newId'; /* We cannot use the same ID */
        ev.target.appendChild(nodeCopy);
      }
    </script>
  </head>
  <body>
    <h2>Drag and Copy</h2>
    <p>Drag and Copy Entered Data from one cell to the next.</p>

    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)" contenteditable="true"></div>
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)" contenteditable="true"></div>
    <div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)" contenteditable="true"></div>
  </body>
</html>

`postMessage` behaves differently in Chromium and Firefox

I have a piece of code that behaves differently in Chromium and Firefox.

// window.js
const worker = new Worker("worker.js", { name: "sadsa" });

// worker.js
const worker = new Worker("worker2.js", { name: "2" });
const sab = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));

worker.postMessage(0);
Atomics.wait(sab, 0, 0);

// worker2.js
onmessage = ({ data }) => console.log(data);

In Chromium, the worker2 never receives the message because Atomics.wait blocks postMessage, but I want to send the message synchronously.

If checkbox is checked then enable all input field

I’m having a trouble with enabling the input fields via a checkbox in the modal dialog. I tried using the code below but it only works with the first data in the modal. When I closed the modal and select the other user, it is not working.

FIRST DATA: Works fine!
1

SECOND DATA: As you can see the EDIT button was enabled but the input fields is not.
2

SCRIPT:

<script>

function enableFields() {

    var cb_edit=document.getElementById("cb_edit");

    if(cb_edit.checked) {
      document.getElementById("user_type").disabled = false;
      document.getElementById("stat").disabled = false;
      document.getElementById("dept").disabled = false;
      document.getElementById("fname").disabled = false;
    } else {
      document.getElementById("user_type").disabled = true;
      document.getElementById("stat").disabled = true;
      document.getElementById("dept").disabled = true;
      document.getElementById("fname").disabled = true;
    }
}

</script>

CHECKBOX BUTTON:

<input class="form-check-input" type="checkbox" id="cb_edit" onclick="enableFields();">
<label class="form-check-label" for="flexSwitchCheckDefault">Edit</label>

Is there a rich-text editor out there that has CodePen embedding built into it?

I’m thinking about building a website that is made out of leaf’s that are potentially interpreted strings. It’s basically codepen, except without being just a site for coding. The idea is to have a single, central location to post, well, string.

Just imagine: you post a codepen on there that is a whole website. Or, you simply post a message. You get the idea.

I figure codepen is exactly what I want to use to do this, inside of an rte (or somesuch). Is there anything out there that already does this? Am I overlooking anything?

All insight is greatly appreciated. 😀