Unable to use the response gathered by Fetch API and use it in my code later

I’m trying to build a HTML, CSS, JS website and want to incorporate an API and use the response further in my website.

I’ve managed to make this API part work but I’m stuck with the final part.

  • What I’ve Achieved

    1. Executing a JS function using FETCH that makes a POST Call with Auth Headers
    2. Getting the response to show up inside my Chrome Developer Console.
  • What I’m trying to achieve

    1. Use the Response (Web URL) that is being received by the POST API Call inside my
      website as a variable. So when the user hits a button this response (URL) opens up in
      a new tab.

In simple terms, I want the make use of the web url that shows up in the Chrome Console.

Here is the code I’m using

  function initiateIDV(){

  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.append("Authorization", "Basic xxxxxxxxxxxxx");
  
  var raw = JSON.stringify({
    "customerInternalReference": "Will's App",
    },
    "userReference": "test-app",
    "tokenLifetime": "10m"
  });
  
  var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
  };

  
  fetch("https://[hidden]/api/v1/accounts", requestOptions)

    .then(response => response.json())
    .then(result => console.log(result.web.href))
    .catch(error => console.log('error', error));   
   
}

My module’s function isn’t triggered and comes out as undefined [duplicate]

I haven’t changed anything in my web app but now I get a “Uncaught ReferenceError: updateTicket is not defined
at HTMLButtonElement.onclick ((index):1:1)”

I have an index.html where I have “tickets” automatically inserted. The tickets are generated in my app.js file and include buttons that trigger the updateTicket() function I have in my app.js. I now get the mentioned error whenever I try to updateTicket().

Button Function Trigger inside Ticket

<button type="button" class="btn btn-outline-primary" id="${doc.id}" 
                onclick="updateTicket(this,
                document.getElementById('tracking${doc.id}').value,
                document.getElementById('carrier${doc.id}').value,
                document.getElementById('supplier${doc.id}').value,
                document.getElementById('supplierContact${doc.id}').value,
                document.getElementById('supplierPhone${doc.id}').value,
                document.getElementById('notes${doc.id}').value,
                '${testValue(doc.data().status)}',
                document.getElementById('buyPrice${doc.id}').value,
                document.getElementById('shipPrice${doc.id}').value)">
                UPDATE</button>

My updateTicket() function. (It invokes a firebase call to update the firestore database)

function updateTicket(e, tracking, carrier, supplier, supplierContact, supplierPhone, notes, status, buyPrice, shipPrice) {
console.log("Update Ticket");
db.collection("orders").doc(e.id).update(
    {
        notes: notes,
        tracking: tracking,
        carrier: carrier,
        supplier: supplier,
        supplierContact: supplierContact,
        supplierPhone, supplierPhone,
        status: status,
        // time: String(Date()).substring(0,21).trim()
        time: Date(),
        buyPrice: buyPrice,
        shipPrice: shipPrice
        
        
    });

}

This is my import in index.html

<script defer src="app.js" type="module"></script>

What is the best way to debug a custom Squarespace JSON-T web application?

So, a few years ago (2019), I built a custom Squarespace web application for one of my Church’s podcast channels. They were using Squarespace for all of their web properties, so that’s what I had to work with. I took a standard HTML template, deconstructed how to follow Squarespace’s templating system, and used a combination of their JSON-T markup paired with the JSON data every Squarespace page returns to establish a functional system of calling the blog/podcast data (aka, collections) and populating archives/single posts accordingly.

At some point, Squarespace introduced 7.1 and things slowly got weird. I noticed that podcast posts were beginning to produce superficial console errors on their backend – but everything was still functional (sort of like the kind of syntax errors you could get with a schema markup, but overall type designation still works). Fast forward to now, the Squarespace markup is just not behaving as expected.

I’ve included the problematic code for reference.

<squarespace:query collection="podcast" skip="1">
{.repeated section items}
<div class="col-sm-12 mb-40 catchItems">
<div class="podcast-card full">
<figure class="podcast-image">
<a href="{website.fullUrl}{fullUrl}">
<img src="{assetUrl}" alt="{title}" title="{title}" /></a></figure>
<div class="podcast-content">
<span class="podcast-date">{addedOn|date %B %e, %G}</span>
<h2 class="podcast-title">
<a href="{website.fullUrl}{fullUrl}">{title}</a></h2>
<p class="podcast-excerpt">
<a href="{website.fullUrl}{fullUrl}">{excerpt}</a></p>
<ul class="podcast-meta">
<li class="item">
<a href="{website.fullUrl}{fullUrl}" class="podcast-play"><i class="fa fa-play"></i> Play Episode</a></li>
</ul></div></div></div>
{.end}
</squarespace:query>

Normal behavior would call ALL the podcasts, but that is not what’s happening.

Upon viewing the “page source”, the collection stops enumeration after 20 posts (which it did not do previously), and there doesn’t appear to be any settings in their CMS backend to explain the change. All the pods still exist on Squarespace’s backend.

As there doesn’t appear to be any errors in the code itself (not that I really have any options when it comes to debugging their platform), I’m not really sure where to go from there.

What’s worse is that Squarespace’s JSON-T documentation is mediocre at best. Squarespace may have changed or updated how their JSON-T works. Or not. I can’t tell. Their documentation doesn’t appear to make any references one way or the other.

I had to patch together my understanding based on other dev stories and blogs. Their support team won’t touch it and has historically been underwhelming.

Does anyone with JSON-T/Custom Squarespace dev experience know what’s going on here? Does anyone know how or have a method to debugging JSON-T for errors? All leads are appreciated. Thanks!

How do I resolve Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop while setting a state?

I am getting an object location from another page like this.

const location = useLocation();

I am trying to set a variable like this.

if (location.state!==null ){
    console.log(location.state.name.companyName)
   setcompanyOneAlready(location.state.name.companyName);
    console.log(companyOneAlready);
   
}

But this results in a Too many renders error. I realise its because of the way I am setting companyOneAlready but I don’t know how to correct this. Any help is appreciated.

checking if an object contains any values besides expected ones

I want to check if an object has a value besides pageSize & pageStart & page , these values arent always all there for example sometimes pagestart will be missing if it equals 0. So checking the length of the object isnt reliable.

let object = {
pageStart: 50,
page: 2
userName: “Bobby”
}

I want to check if the object contains anything besides these values and return a true/false.

Using Promise.all but only want the value of 2 of the resolved promises?

I understand that I can do this to make things cleaner:

const [result2, result3] = await Promise.all([p2, p3]);

but i have the following code where I only care about the values of 2 of the promises. Is there I way I can adapt this following code to be cleaner like the above?

// array of other Promises
this.allAwaitingPromises = [p1, p4];

await Promise.all(this.allAwaitingPromises);
const result2 = await p2();
const result3 = await p3(); 

Unable to exit nested while loop

var userName = input.question('Please enter your name: ');
console.log('nHi ' + userName + ', please select your choice:');
var choice = input.question('1. Display Name 2. Display Age');
while (choice == 1 {
 console.log ("Hello");
 var choice = input.questionFloat('1. Display Name 2. Display Age');
}
while (choice == 2 {
 console.log ("Hello");
  var subChoice = input.question('1. Display date 2. Display time');
  while (subChoice == 1) {
             console.log ("Hello");
  }
  while (subChoice == 2) {
             console.log('nHi ' + userName + ', please select your choice:');
             var choice = input.questionFloat('1. Display Name 2. Display Age');
  }
}

The first block of code is asking the user their name, after which the user will be required to enter either choice 1 or 2.

The choice that the user chose will be stored in the “choice” variable. I have both “choice” as well as “subChoice”. “subChoice” comes after the user select “choice”. In this case, in order to access the subChoice 1 or 2, the user will have to select choice 2 first. If I want to exit the subChoice, I would have to select subChoice 2 which will bring me back to the choices for choice 1 & 2.

However, the problem that I am facing is that after returning to choice 1 or 2, the variable userName does not contain anymore value or string. In addition, when I select other choices i.e choice 1, it does not do anything but re-prompting me the same thing with no userName and loops in the subChoice == 2 itself.

Problem with radio button using map function [duplicate]

I have a list of names in an array and am generating two radio buttons as Present and Absent corresponding to all names using the map function. Now when I select a single present button for any name, all present buttons get selected for all names and the same for absent buttons too.

import React, { useState } from "react";
import Axios from "axios";

function Attendance() {
  const [attedanceList, setAttedanceList] = useState([]);
  const [attendanceMarking, setAttendanceMarking] = useState([]);

  Axios.get("http://localhost:9000/attendance").then((response) => {
    setAttedanceList(response.data.data.values);
  });

  function changeValue(event) {
    let value = event.target.value;
    // console.log([value]);

    setAttendanceMarking((attendanceMarking) => {
      return [...attendanceMarking, value];
    });
    // console.log(attendanceMarking);
  }

  function sendAllValues() {
    Axios.post("http://localhost:9000/attendance", { attendanceMarking });
  }

  return (
    <form>
      {attedanceList.map((val, index) => {
        if (index !== 0) {
          let attendance = "attendance" + index;
          let present = "present" + index;
          let absent = "absent" + index;
          return (
            <div key={index}>
              <div>
                {val[0]} {val[1]}
                <input
                  type="radio"
                  id={present}
                  name={attendance}
                  value="1"
                  checked={attendanceMarking === "1"}
                  onChange={changeValue}
                />
                <label for={present}>Present</label>
                <input
                  type="radio"
                  id={absent}
                  name={attendance}
                  value="0"
                  checked={attendanceMarking === "0"}
                  onChange={changeValue}
                />
                <label for={absent}>Absent</label>
              </div>
            </div>
          );
        }
      })}
      <button type="submit" onClick={sendAllValues}>
        Submit
      </button>
      <div>
        <p>
          Selected <strong>{attendanceMarking}</strong>
        </p>
      </div>
    </form>
  );
}

export default Attendance;

Also, how can I save the state of all radio button selections as a whole so that I can use those value in my backend?

Problem with radio button using map function

I have a list of names in an array and am generating two radio buttons as Present and Absent corresponding to all names using the map function. Now when I select a single present button for any name, all present buttons get selected for all names and the same for absent buttons too.

import React, { useState } from "react";
import Axios from "axios";

function Attendance() {
  const [attedanceList, setAttedanceList] = useState([]);
  const [attendanceMarking, setAttendanceMarking] = useState([]);

  Axios.get("http://localhost:9000/attendance").then((response) => {
    setAttedanceList(response.data.data.values);
  });

  function changeValue(event) {
    let value = event.target.value;
    // console.log([value]);

    setAttendanceMarking((attendanceMarking) => {
      return [...attendanceMarking, value];
    });
    // console.log(attendanceMarking);
  }

  function sendAllValues() {
    Axios.post("http://localhost:9000/attendance", { attendanceMarking });
  }

  return (
    <form>
      {attedanceList.map((val, index) => {
        if (index !== 0) {
          let attendance = "attendance" + index;
          let present = "present" + index;
          let absent = "absent" + index;
          return (
            <div key={index}>
              <div>
                {val[0]} {val[1]}
                <input
                  type="radio"
                  id={present}
                  name={attendance}
                  value="1"
                  checked={attendanceMarking === "1"}
                  onChange={changeValue}
                />
                <label for={present}>Present</label>
                <input
                  type="radio"
                  id={absent}
                  name={attendance}
                  value="0"
                  checked={attendanceMarking === "0"}
                  onChange={changeValue}
                />
                <label for={absent}>Absent</label>
              </div>
            </div>
          );
        }
      })}
      <button type="submit" onClick={sendAllValues}>
        Submit
      </button>
      <div>
        <p>
          Selected <strong>{attendanceMarking}</strong>
        </p>
      </div>
    </form>
  );
}

export default Attendance;

Also, how can I save the state of all radio button selections as a whole so that I can use those value in my backend?

Uncaught TypeError: weather is undefined in React + weatherbit

im working with react and weatherbit api , when i call my data array i have an error with weather object , here is my code …

import React from "react";

const CityWeather = ({data, cityName}) => {
const {weather, app_temp, wind_spd, temp} = data
return (

{cityName}
{temp}

{app_temp}

{wind_spd}

{weather.description}

        </div>

    </div>
)

}

export default CityWeather

and here is my api url in another component…

    useEffect(() => {
    if(!town)return;
    let url = `https://api.weatherbit.io/v2.0/current?lat=${town.latitud}&lon=${town.longitud}&key={APIKEY}1&include=minutely`;
    api.get(url).then((res)=>{
        if(!res.err){
            setData(res);
            console.log(res)
        }
    })

functions result is NaN

I am really new in coding therefore I am coding currently a Taximeter. Unfortunately is the result of my code when executing NaN in the console. I tried some ways to rectify my problem but those attempts did not work. I think that some variables are not in the right scope but I do not know how to fix that.

function Taximeter() {

    const y = 3.9;
    const km =  prompt("How far is your target");
    
    if (km <= 7) {
        var routePrice = 2.3;
        }   else if (km > 7) {
            let routePrice = 1.65
        var subtractedLength = km -= 7;
        var partialExpenses = subtractedLength *= routePrice ;
        var tosevenExpenses = 7 *2.3;
        var combinedExpenses = tosevenExpenses += partialExpenses;
        }
      
        const persons = prompt("How much persons are driving with you?");
        if (persons > 8) {
            console.log("Only 8 persons can drive with you.");
        } else if (8 >= persons >= 5) {
            var personsExpenses = 5;
        } else if (0 >= persons >= 4) {
              personExpenses = 0;
        }
    
        if (km <= 7) {
            var wholeExpenses = y + km * routePrice + personsExpenses;
        } else  {
        var wholeExpenses = combinedExpenses + y + personsExpenses; 
        }
        console.log(wholeExpenses)
    };

consumir una API con Strapi [closed]

Necesito utilizar una Api creando contenido en Strapi, es decir, teniendo mi front-end que le pegue al CMS Strapi, no sabria como montar toda esa estructura desde mi archivo java script para comunicarme con el CMS ( en este caso sin pasar por el backend)

i want to loop through an array but i dont wanna use for can somebody help me please?

function CreateSuspectObjects(name){
    return {
        name: name,
        color: name.split(' ')[1],
        speak(){
            console.log("my name is" , name);
        } 
    };
}; 

a function that takes name as value and return it as an object.

var suspects = ['miss scarlet','colonel mustard','mr white'];

var suspectsList = [];

var _ = {}; 

i get error whether i create this var or not. i dont know why.

_.each(suspects , function(name){
    let suspectObj= CreateSuspectObjects(name);
    suspectsList.push(suspectObj);
}); 

i used each bc i didnt want to use for

Establishing a socket connection between Flask-SocketIO and socket.io-client in a React component

I’m having difficulties when dealing with socket communications between a React app and a Flask backend.

The frontend is based off of this documentation. It contains a button that sends a “ping” event to the backend, as well as a listener for when the backend connects (“after connect”).

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:5000');

function Test() {
  useEffect(() => {
    socket.on('after connect', (message) => {
      console.log("CONNECTED", message);
    });

    socket.on('pong', () => {
      console.log("PONG");
    });

    return () => {
      socket.off('connect');
      socket.off('pong');
    };
  }, []);

  const sendPing = () => {
    console.log(socket.connected);
    console.log("PING");
    socket.emit('ping');
  }

  return (
    <div>
      <button onClick={ sendPing }>Send ping</button>
    </div>
  );
}

export default Test;

The backend contains two routes that handle connection and the ping message. The latter emits a “pong” back.

from flask import Flask
from flask_cors import CORS
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = './temp_upload'
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)

@socketio.on('connect')
def test_connect():
    print("Backend connected. Sending after connect.")
    emit('after connect')

@socketio.on('ping')
def value_changed():
    print("Backend received ping. Sending pong.")
    emit('pong')

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', debug=True)

The behavior that I’m seeing from this code is that test_connect() triggers on the backend, but ‘after connect’ fails to trigger on the frontend once its event is emitted. Also, the function sendPing triggers on the frontend, but value_changed is not triggered on the backend. The ‘pong’ listener on the frontend does trigger every ~25 seconds however, independently of if sendPing is called. Why am I seeing such strange behavior, when I expect to see an indication of connection followed by a PONG when I click on the button that issues PING?

Library versions are:

Highlight the sentence in the paragraph

“I want to highlight the sentence just when I click on it in the paragraph but also to be able to programmatically select a “span” without clicking on it (I need this when the reading continues from span to span for using sound mp3 purpose).

Can it also allow for line breaks br in the paragraph

I hope that it is possible to make these changes in my code. Just FYI, My application has 500 paragarphs. Each paragaraph has 30 sentences and when I click play button, it reads sentence by sentence with highlight each sentence one by one with start and end timing until it finish reading that paragraph.”

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <style>
  .highlight {
  background-color: yellow;
}
</style>
</head>
<body>
<!--
<div><p id="debug">||---||</p></div>
-->
</body>
</html> 
<script>
   var oSentence = "sntnce1";
    var nSentence = 'b';
      document.write(window.AppInventor.getWebViewString());


        window.smoothScroll = function (target) {
            var scrollContainer = target;
            do { //find scroll container
                scrollContainer = scrollContainer.parentNode;
                if (!scrollContainer) return;
                scrollContainer.scrollTop += 1;
            } while (scrollContainer.scrollTop == 0);

            var targetY = 0;
            do { //find the top of target relatively to the container
                if (target == scrollContainer) break;
                targetY += target.offsetTop;
            } while (target = target.offsetParent);

            scroll = function (c, a, b, i) {
                i++;
                if (i > 30) return;
                c.scrollTop = a + (b - a) / 30 * i;
                setTimeout(function () {
                    scroll(c, a, b, i);
                }, 20);
            }
            // start scrolling
            scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);

        }


  

       window.setInterval(function () {

        nSentence = window.AppInventor.getWebViewString();
        if (nSentence.length < 10) {         

            if (nSentence !== window.oSentence) {
                document.getElementById(nSentence).classList.add("highlight");
                var elem1 = document.getElementById(window.oSentence);
                if(typeof(elem1) != 'undefined' && elem1 != null){
                    elem1.classList.remove("highlight");
                }
                var target = nSentence.substr(6) - 1;
                var elem2 = document.getElementById("sntnce"+target);
                if(typeof(elem2) != 'undefined' && elem2 != null) {
                    smoothScroll(elem2);
                }

                window.oSentence = nSentence;             
            }
        }
    }, 1000);

    smoothScroll(document.getElementById('sntnce1'));


  
paragraph = document.getElementById("test");
paragraph.innerHTML = '<span>' + paragraph.textContent.trim().replaceAll(/.s/g,'. </span><span>')
  + '</span>';

 sentences = paragraph.querySelectorAll('span');
sentences.forEach(s => s.addEventListener('click', highlight));
function highlight(event) {
  sentences.forEach(s => s.classList.remove('selected'));
  event.target.classList.add('selected');
}
</script>