Agregar un producto de una tabla a la tabla de ventas?

Necesito agregar un producto que al dar clic en el botón de añadir de la tabla productos y pasar ese producto a la tabla de ventas para seguir añadiendo mas productos, pero el problema es que no puedo agregarlos, probe con input pero solo se agrega uno en en la tabla no se agrega. ayuda porfavor una sugerencia

 <!--tabla de venta en donde debera añadirse los productos-->
 
   <div class="form-group col-lg-3 col-md-3 col-sm-6 col-xs-12">
     <a data-toggle="modal" id="btnAgregarProd">
       <button  type="button" class="btn btn-primary"><span class="fa fa-plus" data-toggle="modal"></span>Agregar producto</button>
     </a>
    </div>
<div class="form-group col-lg-12 col-md-12 col-xs-12">
    <div class="container">
        <div class="row">
                <div class="col-lg-12">
                    <div class="table-responsive"> 
     <table id="detalles" class="table table-striped table-bordered table-condensed table-hover">
       <thead class="text-center" style="background-color:#A9D0F5">
        <th>Opciones</th>
        <th>Cod. producto</th>
        <th>Producto</th>
        <th>Cantidad</th>
        <th>Precio Venta</th>
        <th>Subtotal</th>
       </thead>
         <tbody>
         
         </tbody>
       <tfoot>
         <th>TOTAL</th>
         <th></th>
         <th></th>
         <th></th>
         <th></th>
         <th><h4 id="total">$ 0.00</h4></th>
       </tfoot>
       <tbody>
         
       </tbody>
     </table>
    </div>
                    <!--<input type="text" id="codigo">
                    <input type="text" id="nombre">
                    <input type="text" id="descripcion">
                    <input type="text" id="nomDesc">
                    <input type="text" id="pvp">-->
                    
            </div>
        </div>
    </div>
      </div>
    <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <button class="btn btn-primary" type="button" id="btnGudardar" onclick="btnGuardar()"><i class="fa fa-save"></i>  Guardar</button>
      <button class="btn btn-danger" type="button" id="btnCancelar" onclick="btnCancel()"><i class="fa fa-arrow-circle-left"></i> Cancelar</button>
    </div>
    
    
  <!-- Este es el modal donde estan los productos para agregar a la tabla de venta-->
  
 <div class="modal fade" id="modalProd" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
            </div>
        <form id="formPro">    
            <div class="modal-body">

              <?php 
            $consulta = "SELECT pr.codigo, pr.nombre, pr.descripcion,
                 pr.precio_unitario, pr.stock
                 from productos pr
                 inner join subcategoria su on pr.id_subcategoria = su.id
                 inner join categoria cat on su.id_categoria = cat.id";
                $resultado = $conexion->prepare($consulta);
                $resultado->execute();
                $data=$resultado->fetchAll(PDO::FETCH_ASSOC)

                
            ?>

            
          <div class="container">
        <div class="row">
                <div class="col-lg-12">
                    <div class="table-responsive">        
                        <table id="tablaProd" class="table table-striped table-bordered table-condensed table-hover" style="width:99%">
                        <thead class="text-center" style="background-color:#007EFA; color:#ffffff" >
                             <tr>
                                 
                                <th>Codigo</th>
                                <th>Producto</th>
                                <th>Descripcion</th>                                       
                                <th>PVP</th> 
                                <th>Stock</th> 
                                 <th>Opcion</th>
                                
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                                $cont = 1;
                            foreach($data as $dat2) {                                                        
                            ?>
                            <tr>
                                
                              
                                
                                <td><center><?php echo $dat2['codigo'] ?></center></td>
                                <td><?php echo $dat2['nombre'] ?></td>
                                <td><?php echo $dat2['descripcion'] ?></td>
                                <td>$ <?php echo $dat2['precio_unitario'] ?></td>
                                <td><?php echo $dat2['stock'] ?></td>
                                
                                <input type="hidden" id="cod_<?php echo $cont; ?>" value="<?php echo $dat2['codigo']; ?>">
                                
                                <input type="hidden" id="nombrep_<?php echo $cont; ?>" value="<?php echo $dat2['nombre'] ?>"> 
                                <input type="hidden" id="descripcion_<?php echo $cont; ?>" value="<?php echo $dat2['descripcion'] ?>">
                                <input type="hidden" id="nomDesc_<?php echo $cont; ?>" value="<?php echo $dat2['nombre'].' '.$dat2['descripcion'] ?>"> 
                                <input type="hidden" id="pvp_<?php echo $cont; ?>" value="<?php echo $dat2['precio_unitario']; ?>">
                                   
                                
                                  <td><div class='text-center'><div class='btn-group'><button type='button' class='btnAg' style='background-color:#D6D9E3; border:1.5px solid #187CEB;border-radius: 10px 100px / 120px;' onclick="agregar(document.getElementById('cod_<?php echo $cont; ?>').value,document.getElementById('nombrep_<?php echo $cont; ?>').value,document.getElementById('descripcion_<?php echo $cont; ?>').value,document.getElementById('nomDesc_<?php echo $cont; ?>').value,document.getElementById('pvp_<?php echo $cont; ?>').value)" class="boton"><span class='fa fa-plus'></span></button></div></div></td>
                                
                                
                                <script>
                                                           
                                                            var cod_row = "";

                                                            function agregar(cod,nom,des,nd,pvp) {
                                                                $('#modalProd').modal('hide');
                                                                var Myelement = document.getElementById("codigo");
                                                                Myelement.value = cod;
                                                                var Myelement = document.getElementById("nombre");
                                                                Myelement.value = nom;
                                                                var Myelement = document.getElementById("descripcion");
                                                                Myelement.value = des;
                                                                var Myelement = document.getElementById("nomDesc");
                                                                Myelement.value = nd;
                                                                 var Myelement = document.getElementById("pvp");
                                                                Myelement.value = pvp;
                             
                                                               
                                                                id_row = cod;
                                                            }
                                                        </script>
                                
                            </tr>
                            <?php
                                $cont = $cont + 1;
                                }
                            ?>                                
                        </tbody> 
                       </table>                    
                    </div>
                </div>
    
        </div>  
    </div> 
                        
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-dismiss="modal">Cerrar</button>
                
            </div>
        </form>    
        </div>
    </div>
</div>   

enter image description here

enter image description here

dynamodb query with GSI and filter expression on non partition key and sort key columns in nodejs

I have a GSI on my table and am using that GSI for quering results. Am using a Filter Expression as well

const active_cases = await storesMonthlyAudit();
console.info("actives cases : ", active_cases)

async function storesMonthlyAudit() {
    const params = {
        TableName: "jms-case-management-dev",
        IndexName: "entity-sKey-index",
        ProjectionExpression: "storeId,caseId",
        KeyConditionExpression: "#entity = :entity",
        FilterExpression: "#status = :status",
        ExpressionAttributeNames: {
            "#entity": "entity",
            "#status": "status",
        },
        ExpressionAttributeValues: {
            ":entity": "Case",
            ":status": "Active"
        }
    };
    const cases = await Query(params);
    return cases
}

response :

actives cases :  {
  Items: [],
  Count: 0,
  ScannedCount: 8012,
  LastEvaluatedKey: { entity: 'Case', sKey: 'C#10134066', pKey: 'ST#1013' }
}

But when i tried the same thing from AWS console, it gives me the correct result of 2 records with status = “Active”

enter image description here

Spread operator “is not defined” when trying to omit property [duplicate]

I’m new to react, i’m trying to do something that should be very simple: use the spread operator (…) to create a copy of an object OMITTING ONE PROPERTY…

I’ve tried to follow some posts here, when i test then in javascript emulator they work, but they dont work in my real case

const obj = { a : 'a', b : 'b', c : 'c'};
const [formData, setFormData] = useState({a,...obj});

console.log(formData);

I get the error

Uncaught ReferenceError: a is not defined

Display Image whenever an update is detected using JavaScript

I’m currently working on a website that has an image file that is frequently overwritten, but since the website doesn’t automatically update the image when it is changed, I’m trying to re-display the image whenever it senses a change in the file.

Currently, this is the part that displays the image:

<script>
    const fs = require('fs');
   function updateImage() {
            var image = document.getElementById("img");
            image.src = image.src.split("?")[0] + "?" + new Date().getTime();
    }
    fs.watch(document.getElementById("img"), function(eventType, filename) {
        if (event == 'change'){
            updateImage();
        }
    });
</script>

I know from testing that updateImage() works on it’s own, but I was wondering why the fs.watch() isn’t detecting when the image file gets overwritten. Also, does fs.watch() constantly check for updates or do I need to constantly loop to check for updates?

Thank you!

Refresh Google OAuth2 Token Automatically

I’m trying implement a photo uploading to Google Drive feature (using the Google Drive API and GIS) into a web app that I’m working on, but can’t seem to figure out how to keep a user authenticated for longer than the designated expiry time of the access token (which is 1 hour) without prompting the user or opening a popup.

The sample code provided at https://github.com/googleworkspace/browser-samples/blob/master/drive/quickstart/index.html forces the user to click a “refresh” button to get a new token, but this means I would have to force users to sign in every hour, which isn’t ideal (since users are likely going to be using the app for periods longer than an hour at a time).

According to https://developers.google.com/identity/oauth2/web/guides/use-token-model#token_expiration, this appears to be intentional. However, after looking around quite a bit, I found that one could supposedly use a refresh token to generate a new access token that expires after another hour. Assuming you generate a new token every 45 minutes or so (which another Google article actually suggested, but I can’t seem to find it now), then you should never have to worry about this re-authentication.

However, I can’t figure out how to get a refresh token.

Not receiving Google OAuth refresh token suggests sending access_type=offline as a query parameter, but I’m not using any redirects, and the aforementioned documentation for initTokenClient and requestAccessToken don’t make any mention of an access_type parameter.

The closest I’ve gotten is calling the requestAccessToken method periodically, but this still brings up a popup for the user to sign in again, which is what I’m trying to avoid. Even using requestAccessToken({ prompt: "" }) still brings up this popup window, but it at least logs in without any user input. Is there any way to disable this popup window entirely?

Worst case scenario, I force the user to re-authenticate every hour, but this seems like it would make for a less-than-ideal UX. Any help is appreciated.

jest-dom eslint rule violation not breaking test

I’m using Reactjs with CRA. I have a test like this;

enter image description here

I’m deliberately forcing jest-dom to produce this prefer-to-have-text-content warning. My test still runs OK and the result is success. Now, I want my test to fail. My .eslintrc file is like;

{
  "plugins": ["testing-library", "jest-dom"],

  "extends": [
    "react-app",
    "react-app/jest",
    "plugin:testing-library/react",
    "plugin:jest-dom/recommended"
  ],
  "rules": {
    "jest-dom/prefer-to-have-text-content": "error"
  }
}

However, my test still succeds!
How can I make my test fail in case of such jest-dom issues?

how to get the url of window hosting my JS code

Problem

I want to get the full url of this topic. Like stackoverflow.com/questions/72080682/...
Though when using standard get url method I get the url hosting my snipped code. stacksniped.net/js or stack over flow’s main url (ending with .com with no more refferences)

Why I need this

I need to know the hosted site url because the same problem happens to me in another app where I want to use the real url for obfuscation and code originality protection. Though it gives some standard url. Then when someone there blindy copies my code it will work for him too.

Here is an example:

console.log('document.location', document.location.href);
console.log('document.refferer',  document.referrer); // Returns path only
console.log('ancestorOrigins', document.location.ancestorOrigins[0]); // Returns full URL

Any help would be appreciated

Object.keys vs Object.value – .keys mutates and .value does not. Why is this?

I am trying to change the values inside an object in Javascript, Object.values while running a forEach loop would seem to make the most sense to me but Object.keys (obj[key]) actually updated the value on the object. Here is my code to explain better.

This way below works as expected

const usersKey = { user1: 18273, user2: 92833, user3: 90315 }

Object.keys(usersKey).forEach((key) => {
    usersKey[key] = usersKey[key]*2
    
})

console.log(usersKey)

This way below does not update the object


const usersValue = { user1: 18273, user2: 92833, user3: 90315 }

Object.values(usersValue).forEach((value) => {
    value = value*2
    
})

console.log(usersValue) 

Why is this? Shouldn’t both ways produce identical results?

Fixing render function to allow Object with perspective projection

Im having troubles rendering my object after implementing perspective projection. Ive tried adjusting my shaders relative to the JS file, but im still not sure whats wrong. Any help would be highly appreciated! Also, the console isnt showing any errors, its only the rendering of the object that doesnt work.

"use strict";

var canvas;
var gl;

var numVertices  = 36;

var texSize = 64;

var program;

var pointsArray = [];
var colorsArray = [];
var texCoordsArray = [];



//Images
var texture;

var texture2;


//Dimensions of Home

//Needed to multiply the length and the width by 5 b/c the rectangle was too small before hand

var l = 1
var h = .5 
var w = 1

//For Persepctive Distortion
var near = 0.3;
var far = 3.0;
var radius = 4.0;
var theta  = 0.0;
var phi    = 0.0;
var dr = 5.0 * Math.PI/180.0;

var  fovy = 45.0;  // Field-of-view in Y direction angle (in degrees)
var  aspect;       // Viewport aspect ratio

var mvMatrix, pMatrix;
var modelView, projection;
var eye;
const at = vec3(0.0, 0.0, 0.0);
const up = vec3(0.0, 1.0, 0.0);



var texCoord = [
    vec2(0, 0),
    vec2(0, 1),
    vec2(1, 1),
    vec2(1, 0)
];

var vertices = [
   vec4( -l, -w,  h, 1.0 ),
   vec4( -l,  w,  h, 1.0 ),
   vec4( l,  w,  h, 1.0 ),
   vec4( l, -w,  h, 1.0 ),
   vec4( -l, -w, -h, 1.0 ),
   vec4( -l,  w, -h, 1.0 ),
   vec4( l,  w, -h, 1.0 ),
   vec4( l, -w, -h, 1.0 )


];



var vertexColors = [
    

    //Needed to set color to white inorder to for the images to be visable
    vec4( 1.0, 1.0, 1.0, 1 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 1.0, 1.0, 1.0, 1.0 ),  // white

];

//For images

function configureTexture(image,image2) {
    
    //this is for picture of the wall
    
    texture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, texture );
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image );
    gl.generateMipmap( gl.TEXTURE_2D );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
    gl.uniform1i(gl.getUniformLocation(program, "texture"), 0);


    //this is for picture of deques
    
    texture2 = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, texture2 );
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image2 );
    gl.generateMipmap( gl.TEXTURE_2D );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
    gl.uniform1i(gl.getUniformLocation(program, "texture2"), 0);
    

}


function quad(a, b, c, d) {


    //Lighting direction
    /*
    var t1 = subtract(vertices[b], vertices[a]);
    var t2 = subtract(vertices[c], vertices[b]);
    var normal = cross(t1, t2);
    var normal = vec3(normal);
    */


     pointsArray.push(vertices[a]);
     //normalsArray.push(normal);
     colorsArray.push(vertexColors[a]);
     texCoordsArray.push(texCoord[0]);

     pointsArray.push(vertices[b]);
     //normalsArray.push(normal);
     colorsArray.push(vertexColors[a]);
     texCoordsArray.push(texCoord[1]);

     pointsArray.push(vertices[c]);
     //normalsArray.push(normal);
     colorsArray.push(vertexColors[a]);
     texCoordsArray.push(texCoord[2]);

     pointsArray.push(vertices[a]);
     //normalsArray.push(normal);
     colorsArray.push(vertexColors[a]);
     texCoordsArray.push(texCoord[0]);

     pointsArray.push(vertices[c]);
     //normalsArray.push(normal);
     colorsArray.push(vertexColors[a]);
     texCoordsArray.push(texCoord[2]);

     pointsArray.push(vertices[d]);
     //normalsArray.push(normal);
     colorsArray.push(vertexColors[a]);
     texCoordsArray.push(texCoord[3]);
}


function colorCube()
{
    quad( 1, 0, 3, 2 );
    quad( 2, 3, 7, 6 );
    quad( 3, 0, 4, 7 );
    quad( 6, 5, 1, 2 );
    quad( 4, 5, 6, 7 );
    quad( 5, 4, 0, 1 );
}


window.onload = function init() {

    canvas = document.getElementById( "gl-canvas" );

    gl = WebGLUtils.setupWebGL( canvas );
    if ( !gl ) { alert( "WebGL isn't available" ); }

    gl.viewport( 0, 0, canvas.width, canvas.height );

    aspect =  canvas.width/canvas.height;

    
    //Set canvas to black
    gl.clearColor( 0, 0, 0, 1 );

    gl.enable(gl.DEPTH_TEST);

    //
    //  Load shaders and initialize attribute buffers
    //
    program = initShaders( gl, "vertex-shader", "fragment-shader" );
    gl.useProgram( program );

    colorCube();

    


    var cBuffer = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );

    var vColor = gl.getAttribLocation( program, "vColor" );
    gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vColor );

    var vBuffer = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );

    var vPosition = gl.getAttribLocation( program, "vPosition" );
    gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vPosition );

    var tBuffer = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, tBuffer );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(texCoordsArray), gl.STATIC_DRAW );

    var vTexCoord = gl.getAttribLocation( program, "vTexCoord" );
    gl.vertexAttribPointer( vTexCoord, 2, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vTexCoord );

    modelView = gl.getUniformLocation( program, "modelView" );
    projection = gl.getUniformLocation( program, "projection" );


    //Image of the wall (1) and deques (2)
    var image = document.getElementById("texImage");
    var image2 = document.getElementById("texImage2");
    configureTexture(image,image2);


    //Button to stop rotation
    document.getElementById("ButtonT").onclick = function(){flag = !flag};
    
    render();

}



var render = function(){
    
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    
    
    eye = vec3(radius*Math.sin(theta)*Math.cos(phi),
    radius*Math.sin(theta)*Math.sin(phi), radius*Math.cos(theta));
    mvMatrix = lookAt(eye, at , up);
    pMatrix = perspective(fovy, aspect, near, far);

    
    //Placing the image of deque on the larger face of the building
    gl.bindTexture( gl.TEXTURE_2D, texture2);
    gl.uniform1i(gl.getUniformLocation(program, "texture"), 0);
    gl.drawArrays( gl.TRIANGLES, 0, 6);


    //Wrapping the sides of the building with images of the wall
    
   gl.bindTexture( gl.TEXTURE_2D, texture );
   gl.uniform1i(gl.getUniformLocation(program, "texture"), 0);
   gl.drawArrays(gl.TRIANGLES,6,numVertices-6);
   

   gl.uniformMatrix4fv( modelView, false, flatten(mvMatrix) );
    gl.uniformMatrix4fv( projection, false, flatten(pMatrix) );
   


    
    requestAnimFrame(render);
}
<!DOCTYPE html>
<html>
<style type="text/css">
    canvas { background: rgb(138, 40, 40); }
</style>
<script id="vertex-shader" type="x-shader/x-vertex">


attribute  vec4 vPosition;
attribute  vec4 vColor;
attribute  vec2 vTexCoord;

varying vec4 fColor;
varying vec2 fTexCoord;

uniform vec3 theta;

//lighting
uniform vec4 lightPosition;
uniform float shininess;
uniform vec4 diffuseProduct;
attribute  vec3 vNormal;

//For Persepctive Projection
uniform mat4 modelView;
uniform mat4 projection;

void main()
{

    fColor = vColor;
    fTexCoord = vTexCoord;
    gl_Position = projection * modelView * vPosition;
    gl_Position.z = -gl_Position.z;
}
</script>

<script id="fragment-shader" type="x-shader/x-fragment">

precision mediump float;

varying vec4 fColor;
varying  vec2 fTexCoord;

uniform sampler2D texture;


void
main()
{
   
    
    gl_FragColor = fColor * texture2D( texture, fTexCoord );
}
</script>

<script type="text/javascript" src="../Common/webgl-utils.js"></script>
<script type="text/javascript" src="../Common/initShaders.js"></script>
<script type="text/javascript" src="../Common/MV.js"></script>
<script type="text/javascript" src="FinalProject.js"></script>


<center>  <button id = "ButtonT">Toggle Rotation</button>   </center>
<body>

    <p> </p>
    <button id = "Button1">Increase Z</button>
    <button id = "Button2">Decrease Z</button>
    <button id = "Button3">Increase R</button>
    <button id = "Button4">Decrease R</button>
    
    <p> </p>
    <button id = "Button5">Increase theta</button>
    <button id = "Button6">Decrease theta</button>
    <button id = "Button7">Increase phi</button>
    <button id = "Button8">Decrease phi</button>
    <p> </p>



<center>  <canvas id="gl-canvas" width="600" height="512">
    Oops ... your browser doesn't support the HTML5 canvas element
    </canvas>       </center>

<center> Simplistic Model of the Dequés Building at GWU </center>

<center>---</center> 


<center> Ideas covered in this project: </center>

<center> Double Texture Mapping, Lighting </center>


    
<img id = "texImage" src = "brick copy.jpeg" hidden></img>
<img id = "texImage2" src = "house copy.jpg" hidden></img>
</body>
</html>

Async Function with Promise.All Only Running After Updating Code

I’m writing an asynchronous function in React that should set the “coords” state to an array of objects containing US states and their respective latitudes/longitudes. To do this, I’m making an API call and resolving those calls using Promise.all. On the first refresh of the page, the function works as intended. However, on subsequent refreshes, the function does not execute the Promise.all statement and therefore does not set the coords state. Why is this the case and how can I resolve this issue?

export default function App() {

  const [covidDataJSON, setCovidDataJSON] = useState(null);
  const [stateNames, setStateNames] = useState([]);
  const [coords, setCoords] = useState([]);
  const [stateInfos, setStateInfos] = useState([]);

  useEffect(() => {
    fetchCoords();
  }, [])

  const fetchCoords = async () => {
    try {
      getStateNames();
      const req = await Promise.all(stateNames.map(async (state) => {
        return await axios.get(`https://nominatim.geocoding.ai/search.php?state=${state}&format=jsonv2`);
      }))
      for (let i = 0; i < req.length; i++){
        const stateInfo = req[i].data[0];
        if (req[i].data.length !== 0)
          setCoords(coordsArr => [...coordsArr, {name: stateInfo.display_name, lat: stateInfo.lat, lon: stateInfo.lon}]);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const getStateNames = () => {
    try {
      const stateArr = [];
      for (let i = 0; i < states.length; i++){
        stateArr.push(states[i].name);
      }
      setStateNames(stateArr);
    } catch (error) {
      console.error(error);
    }
  }

Antd Countdown not working for a specific date

I’m trying to create a component to a specific date using react with antd. Here’s my code:

import { Statistic, Col, Row } from 'antd';

const { Countdown } = Statistic;
const deadline = Date.parse('2022-12-31') - Date.now();

const Count = () => {
    return (
        <Countdown title="Countdown" value={deadline} format="DD:HH:mm:ss"/>
    )
}

The countdown just displays 00:00:00:00 when the timestamp has is a positive number. Any help is appreciated. Thanks!

jQuery progress prevention code stop working

I have this snippet to prevent auto-progress in form on the step where user must select multiple questions. The problem now is that it prevent auto progress, but when user select one of the checkboxes it’s impossible to deselect it. It’s for a plugin on WordPress

(function ($) {
jQuery('#tab .question').on('click', function (e) {
    e.preventDefault();
    $target = jQuery(e.target);
    var isChecked = $target.prev().attr('checked');
    if (isChecked) {
        $target.prev().prop('checked', false);
    } else {
        $target.prev().prop('checked', true);
    }
});
})(jQuery);

Javascript If statement not getting false when it should be

Trying to make a calculator for a triangle to see if the given sides can form one and if it’s a right angle one. I create more buttons for more options to calculate, but I’m having issues with my If statement. When the result should be false it stays true, I’m using the && operator since as I understand it means both conditions on either side of it have to be true for it to proceed and I shouldn’t be having an issue with nested if statements.

If I do 10 for length 1 and then 1 for lengths 2 and 3, it should pass the first part fine since they’re both true, but the nested if statement should come back false since neither length 2 or 3 add up past length 1, but it returns to me as true continues to give me the “can form triangle” text I setup.

    window.onload = function() {
    var testButton = document.getElementById("tests");
    testButton.onclick = addTests;
};

function addTests() {
    var test1 = document.createElement("button");
    test1.innerHTML = "(1) Test whether these three sides can form a triangle";
    document.body.appendChild(test1);
    test1.onclick = function() {
        var answer = document.getElementById("answer");
        var length1 = document.getElementById("length a");
        var length2 = document.getElementById("length b");
        var length3 = document.getElementById("length c");
        
        if (length1 + length2 > length3 && length1 + length3 > length2)
        {
                if (length2 + length3 > length1)
                {
                    result = "These three sides can form a triangle!";
                    answer.innerHTML = result;
                }
                else
                {
                    result = "These three sides cannot form a triangle!";
                    answer.innerHTML = result;
                }
        }
        else
        {
            result = "These three sides cannot form a triangle!";
            answer.innerHTML = result;
        }

    };

How to render a variable from a function

So I’m trying to render a constructor variable but when I add the lines that renders it, the whole page goes blank. I don’t know if it’s that this.balance() is not called there or sm.
I’m new so help is appreciated 🙂

  constructor(props){
    super(props)
    this.state = {
      balance: ""
    }
  }

  balance = async() => {
    const web3 = window.web3
    const balance = web3.eth.getBalance(this.state.account)
    this.setState({balance})
  }

render(){
    this.balance()
    return(
      <section id="payments">
        Payments
        <Nav/>
        <p>balance: {this.state.balance}</p>
      </section>
    )
  }