Fetch & init Param [closed]

I had a quick question I know fetch is a get request by default but when you pass a init with a post method does that override the fetch I’m not sure if that is going on or we are doing a get and then doing a post. Here is a code example:

fetch("http://example.com/api/endpoint/", {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: myName,
    password: myPassword
  })
})
.then( (response) => { 
   //do something awesome that makes the world a better place
});

setting the state inside the useEffect with that state as a dependency

Let’s say I have this code here:

const [a , setA] = useState(false);
useEffect(() => {
      setA(true);

    setTimeout(()=>{
      setA(false);
    },300);

},[a]);

I have two questions:

1) Will this create an infinte loop (if I’m using that same state as a dependency)?

2) If I set the state in the middle of the useEffect code the component re-render immediately, so when will the rest of the code execute if the component render before we get to it inside the useEffect?
When will the setA(false) happen?

How to create a getter and setter for jquery object?

I want to add a getter and a setter for the $ object, similar to the val() function for a DOM object.

If the val is called without parameters, the getter is invoked. With one parameter, the setter is invoked.

I have tried with

$.fn.simpleSearch = function() {
    return _variable;
}

$.fn.simpleSearch = function (search) {
    _variable = search;
}

But it does not work.

Any hint?

CORS returning status 0 and no data

I am trying to fetch data from an API using fetch() on javascript. This is my code

async function getCS() {


    try {
        const response = fetch('http://chargepoints.dft.gov.uk/api/retrieve/registry/lat/51.545581/long/-0.077301/dist/0.2/format/json',
            {
                method: 'GET',
                mode: 'no-cors',
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'content-type': 'application/json'
                }
            })
        return response;
    } catch (error) {
        throw error.message;
    }
}

console.log(getCS());

The request returns Status 0 and I dont get any data. can i get help please

React Select does not change Label according to defaultValue

import React from "react";
import { useState } from "react";
import Select from "react-select";

const EditMitarbeiter = () => {
    const optionsField1 = [
        { id: "1", value: "test1", label: "Test1"},
        { id: "2", value: "test2", label: "Test2"},
        { id: "3", value: "test3", label: "Test3"},
        { id: "4", value: "test4", label: "Test4"},
    ];
    
    const[functions, setFunctions] = useState([
        {field1:"test1",field2:"test2",field3:"test3",input:"Test"}
    ]);

    const handleFunctionAdd = () => {
        setFunctions([...functions, {field1:"",field2:"",field3:"",input:""}]);
    };

    const handleFunctionRemove = (event, index) => {
        event.preventDefault(); // verhindert Default Verhalten von Button, ist somit kein "Submit-Button" mehr und lädt Seite nicht neu
        console.log(index); // FEHLER: este Funktion wird nicht entfernt, sondern folgende
        const list = [...functions];
        list.splice(index,1);
        setFunctions(list);
    };

    const handleFunction1Change = (event, index) => {
        const newFunctions = [...functions];
        newFunctions[index].field1 = event.value;
        setFunctions(newFunctions);
    }

    return (
        <div>
            <div id="content">
                <form id="Funktion">
                    <legend>Funktionen</legend>
                        {functions.map((f,index) => (
                            <div key={index} id="function-box">
                                <div class="ReactSelect"><Select options={optionsField1} defaultValue={f.field1} onChange={(event) => handleFunction1Change(event,index)}/></div>
                            </div>
                        ))}
                </form>
            </div>
        </div>
    );
}

export default EditMitarbeiter;

I got the problem that my the label of the ReactSelect does not change and it stays blank. I already looked through some similar questions but i couldn’t figure out why my example does not work even though i used the solutions of the other questions.

Also a side question, is it worth to use ReactSelect over the normal HTMLSelect cuz i just get problems with the ReactSelect…

How to implement a for loop inside a combineKernel in GPU.js

I’m new to gpu.js and I need help. Basically I want to access my two kernel functions but I don’t know how without sacrificing the expense of calling createKernel each time. I know there is combineKernel but I haven’t seen an example where it uses a for loop inside.

So I have my first function which generates a square matrix from a vector

const functionA = gpu.createKernel(function(vector:number[]) {
   // just body of the code
}).setOutput([somethingLength, somethingLength])

Then from the resulting square matrix, I add each of its columns, and this return a vector. So I have another function for that

const functionB = gpu.createKernel(function (squareMatrix: number[][], initialVector: number[]) {
        let sum = initialVector[this.thread.x]
        for (let i = 0; i < squareMatrixLength ; i++) {
            sum += squareMatrix[i][this.thread.x]
        }
        return sum;
}).setOutput([initialVector.length])

I also have a combineKernel for both of them

const functionC = gpu.combineKernels(functionA as any, functionB as any, function (initialVector: number[], vector: number[]) {
        return functionB(functionA(vector), initialVector)
    })

Now, I have a number of vectors that I want to undergo functionA and then functionB, I want to do something like the code below inside the combineKernel to avoid the expense of cpu to gpu but I am having trouble how to figure it out. I want the final result to be a 2D matrix.

for(let i=0; i<vectorsLength; i++){
   newVector = functionB(functionA(vectors[i]), initialVector)
}
return newVector

Hope you can help me. Thank you!!!

Manipulating a parent tag in JavaScript

I have a simple note taking web 5 application. Each time the user clicks on the ‘+’ button a new note is added. Once he clicks on the ‘⟳’ button all are excluded. I want to add five new item slots in the note that the user clicked. In order to do that I need to know which note he did so. This last bit is the one confusing me. How can I know which button the user clicked if all of the buttons are generated by the user?

HTML:

<html lang="en">
  <head>
    <title>To Do Lists</title>
    <link rel="stylesheet" href="styles.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <div class="top_bar">
      <button id="plus">+</button>
      <button id="restart">⟳</button>
    </div>
    <div id="notes" class="notes">

    </div>
  </body>
</html>

CSS

    padding: 0px;
    margin: 0px;
}
body{
    display: flex;
    flex-direction: column;
}
.top_bar{
    width: 100%;
    height: 10vh;
    background-color: #95E29B;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
button{
    font-size: 35px;
    border: none;
    width: 15%;
    height: 10vh;
    background-color: #3BCE4B;
    cursor: pointer;
}
.notes{
    width: 100%;
    height: 90vh;
    overflow: auto;
    background-color: black;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}

.note{
    margin-top: 20px;
    margin-bottom: 20px;
    margin-left: 20px;
    height: 40vh;
    width: 30%;
    border-radius: 10px;
    background-color: white;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: flex-end;

}

.note_input{
    margin-top: 20px;
    margin-right: 5%;
    font-size: 30px;
    width: 90%;
    border-style: solid;
    border-top: none;
    border-left: none;
    border-right: none;
    border-color: black;
}

form{
    margin-top: 10px;
    margin-right: 15%;
    width: 80%;
    height: 49%;
    overflow-y: auto;
}

li{
    border: none;
    width: 70%;
    display: flex;
}

.li_input{
    border-style: solid;
    border-color: black;
    border-top: none;
    border-left: none;
    border-right: none;
    margin-left: 10px;
    font-size: 20px;
}

.more_items{
    width: 35px;
    height: 35px;
    margin-right: 2%;
    border-radius: 100%;
    font-size: 20px;
}

JavaScript

const add_note = () => {
  // Creates a new note and its props
  const new_note = document.createElement("div");
  const new_input = document.createElement("input");
  const new_form = document.createElement("form");
  const new_ol = document.createElement("ol");
  const new_button = document.createElement("button");

  //Populates the new note with inputs and checkboxes
  for (let i = 0; i < 5; i++) {
    let new_li = document.createElement("li");
    let new_checkbox = document.createElement("input");
    new_checkbox.setAttribute("type", "checkbox");
    let new_li_input = document.createElement("input");
    new_li_input.classList.add("li_input");
    new_ol.appendChild(new_li);
    new_li.appendChild(new_checkbox);
    new_li.appendChild(new_li_input);
  }

  //New note's settings
  new_note.classList.add("note");
  new_note.appendChild(new_input);
  new_input.classList.add("note_input");
  new_input.setAttribute("placeholder", "Note's title");
  new_note.appendChild(new_form);
  new_ol.classList.add("ols");
  new_form.appendChild(new_ol);
  new_note.appendChild(new_button);
  new_button.classList.add("more_items");

  //Inserts the new note and button
  const note_block = document.getElementById("notes");
  note_block.appendChild(new_note);
  new_button.addEventListener("click", add_more_items);
  new_button.innerHTML = "+";
};

//Adds more items
const add_more_items = () => {
  //console.log(new_button.parentElement.nodeName);
  //let new_ol = document.getElementsByClassName("ols")[];
  for (let i = 0; i < 5; i++) {
    let new_li = document.createElement("li");
    let new_checkbox = document.createElement("input");
    new_checkbox.setAttribute("type", "checkbox");
    let new_li_input = document.createElement("input");
    new_li_input.classList.add("li_input");
    new_ol.appendChild(new_li);
    new_li.appendChild(new_checkbox);
    new_li.appendChild(new_li_input);
  }
};

//Removes all notes
const remove_note = () => {
  let amount_of_notes = document.getElementsByClassName("note").length;
  console.log(amount_of_notes);
  while (amount_of_notes != 0) {
    amount_of_notes--;
    document.getElementsByClassName("note")[amount_of_notes].remove();
  }
  alert("All notes were removed.");
};

// Loads the buttons
const load_buttons = () => {
  document.getElementById("plus").addEventListener("click", add_note);
  document.getElementById("restart").addEventListener("click", remove_note);
};

// Main method
document.addEventListener("DOMContentLoaded", () => {
  load_buttons();
});

Thanks in advance.

Why is my function to change the innerText of a targeted button changing the innerText of all the buttons?

This is my first JS project.
I am creating a study scheduler where the user inputs a to-do item and assigns it to a day.
JS creates the necessary elements (input field, trash button, completed button, start time button and end time button). I’m having a problem with the time picker.
I wrote a function that unhides a clock (that I wrote in html) when the user clicks on a startButton (that is created in JS). There can be unlimited startButtons so I wrote an eventListener for the array of these buttons.
The user picks the hour, minutes, and am/pm, which all get stored in variables, and then when they click the setTimeButton, the targeted startButton.innerText should update to show this time. The first time I run the function it works. After that, it is changing the targeted startButton plus every previous startTime button that I have clicked.
Here is the code:

document.addEventListener('DOMContentLoaded', () => 
  Array.from(startButton).forEach(element => 
    element.addEventListener('click', showTimePicker)
) );

function showTimePicker(e) { 

  let startOrEndTimeButton = e.target           
  // show clock
  Array.from(time).forEach(element => element.classList.toggle('hide')) 

  // click setTimeButton to insert time into targeted start time or end time button
  setTimeButton.addEventListener('click', function() {

    startOrEndTimeButton.innerText = chosenHour.innerText 
                                  + ':' + chosenMinutes.innerText 
                                  + " " + chosenAmPm.innerText;
    startOrEndTimeButton.style.backgroundColor = '#39ff14';
    startOrEndTimeButton.style.color = 'white';   
    Array.from(time).forEach(element => element.classList.toggle('hide')); 
  })
} 

Get javascript to edit text in line on html

I am using jinja to spit out integers into my HTML. I want to convert the integer to USD using JavaScript. My product.cost variable gives the integer 100 and my inttousd() function runs, but does not edit the text inside my HTML. Is there a way to get javascript to update inline or do I have to assign a class to each element and update it that way?

Here is myjinja template:

<script>inttousd("{{ product.cost }}")</script>

Here is a javascript function I made to convert the integer to USD. The console.log shows the function running, but inspect shows everything exactly how jinja saw it except product.cost is given as the integer 100.

function inttousd(str) {
    //Add commas for thousands on first slice
    const [dollars, pennies] = [str.slice(0, -2), str.slice(-2)];
    console.log("$"+dollars+"."+pennies)
    return "$"+dollars+"."+pennies;
}

I can’t seem to parse the incoming data from XMLHttpRequest

i tried json parse but not working, either error or nothing showed up.

this is my code

//AJAX XHR

function reqListener(response){
    let data = response.responseText;
    let json = JSON.parse(data)
    console.log('Fetched data: ', data)
    console.log('is woorking!!!')
}


let xhr = new XMLHttpRequest()
xhr.addEventListener('load', reqListener)
xhr.onerror = console.error()
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1')
xhr.addEventListener('error', function(err){
    console.log('errorrr')
})
xhr.send()

can someone help?

How to get sub field of an object javascript [duplicate]

data = {
active: false
address: {
   address_1: '123 Main St', 
   address_2: 'Unit 1', 
   city: 'San Diego', 
   country: 'US', 
   postal_code: '92126'
}
created_at: "2022-05-23T21:28:10.545Z"
created_by: null
id: 1
type: "physical"
updated_at: "2022-05-28T08:09:08.337Z"
warehouse_aliases: []
}

I have a object as above, I want to access the data.address.country dynamically let’s say the dynamic value x = “address.country”. However, when I try to get the value like data[x] it didn’t work. How can I get the value ? Thanks a lot for any answer 🙂

accordian to toggle between paragraph and icon

i tried to create an accordian where click in heading a paragraph will appear and plus icon also disappear and minus icon appear.i set style.display to change between block and none and use if else to match paragraph. I take elements by classname and access element by a for loop. The idea is to change between 2 state of p (p is hide then plus icon is block and p is block plus icon is hide and minus icon is block)

var block = document.getElementsByClassName("block")
var p = document.getElementsByClassName("content")
var plus = document.getElementsByClassName("plus")
var minus = document.getElementsByClassName("minus")
for (let i = 0; i < block.length; i++) {
    block[i].addEventListener('click', function () {
        if (p[i].style.display == "none") {
            p[i].style.display = "block"
            plus[i].style.display = "none"
            minus[i].style.display = "block"
        }
        else if (p[i].style.display == "block") {
            p[i].style.display = "none"
            plus[i].style.display = "block"
            minus[i].style.display = "none"

        }
    })

}
.block {
  display: block;
}
* {
  font-family: "Verdana";
  font-size: 15px;
}
.hide {
  display: none;
}

.header:hover {
  cursor: pointer;
  background: grey;
}
.header {
  padding: 20px;
  background: #cccccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
<!DOCTYPE html>
<html lang="en">
  <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" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link rel="stylesheet" href="/howto/accordion/style.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
      integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <title>Document</title>
  </head>
  <body>
    <div class="block">
      <div class="header">
        <p class="title">Section 1</p>
        <span class="plus"><i class="fa-solid fa-plus"></i></span>
        <span class="hide minus"><i class="fa-solid fa-minus"></i></span>
      </div>
      <p class="content hide">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia
        perferendis qui assumenda at blanditiis dolore nesciunt modi quis alias
        nihil adipisci fugiat architecto, dicta unde, molestias totam delectus
        quam magni!
      </p>
    </div>
    <!-- <div class="block">
      <div class="header">
        <p class="title">Section 2</p>
        <i class="fa-solid fa-plus"></i>
        <i class="fa-solid fa-minus"></i>
      </div>
      <p class="hide">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia
        perferendis qui assumenda at blanditiis dolore nesciunt modi quis alias
        nihil adipisci fugiat architecto, dicta unde, molestias totam delectus
        quam magni!
      </p>
    </div>
    <div class="block">
      <div class="header">
        <p class="title">Section 3</p>
        <i class="fa-solid fa-plus"></i>
        <i class="fa-solid fa-minus"></i>
      </div>
      <p class="hide">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia
        perferendis qui assumenda at blanditiis dolore nesciunt modi quis alias
        nihil adipisci fugiat architecto, dicta unde, molestias totam delectus
        quam magni!
      </p>
    </div> -->
    <script src="js2.js"></script>
  </body>
</html>

Buffer to String with bytes as string

In Node.js I am getting a buffer result as:

<Buffer 21 61 0b>

How can I convert this to a string like this:

“21610b”

All the methods and suggestions I have seen online are for converting the buffer to a string but that will change the layout. I want to keep the exact same layout as string.