Input validation in react with functional component and useEffect hook

Basically I want to reset my quantity to 1 if equal to 0 or less. I understand I need more validation too but this is the first requirement. This this just keep resetting as soon as I start typing which is obvious

Product.component.js

import { useState, useEffect } from "react";
const Product = () => {
    const [qty, setQty] = useState(1);
    useEffect(() => { }, [qty]);
    
    const handleChange = (currentQty) => {
            if (currentQty > 0) {
                console.log("ok");
                //Do Somethong
            } else {
                setQty(1);
            }
        };
    return (
            <input type="text" value={qty} onChange={(e) => handleChange(e.target.value)} />
    );
};
export default Product;

Permissions not showing on mobile ReactJS

I am making this QR code reader for this product that I was hired to make
and I found a road block that I am not able to get over. I added the permissions
code with this code snippet: navigator.mediaDevices.getUserMedia({audio: true, video: true}) and it works on desktop (I can even make it smaller screen and it still works, the popup shows up and everything) but on mobile I go to the public url that I got once I did npm start (which was 192.168.1.126:3000) and I get a full white screen straight away. Not sure what I can do to fix it, I’ve been trying for around 3 days so far and coming here is kind of my last resort. Has anyone ever run into such problem? Is permissions something you can’t do on mobile when you are on devevelopment? Do you know how to fix it?

P.S. I tried 3 different mobile browsers and around 4 qr code scanner packages and they all do the same

Stripe: payment_init.php returns 403 forbidden error code

I am trying to integrate a Stripe payment method in a web application. I am stuck: payment_init.php does not load, when I am redirected to the page. I get 403 Forbidden error code (“Forbidden. You don’t have permission to access this resource.
Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request”).
Here is my payment_init.php file’s code:

<?php

// Include the Stripe PHP library 
require_once 'stripe-php/init.php';

// Include the configuration file 
require_once 'config.php';

$chosenService = $_POST['submitService'];

printf($chosenService);

// Product Details
if ($chosenService === "1") {
    $productName = "Hajvágás (6900 HUF)";
    $productID = "hc001";
    $productPrice = 6900;
} elseif ($chosenService === "2") {
    $productName = 'Hajvágás + Szakáll (9900 HUF)';
    $productID = "hc002";
    $productPrice = 9900;
};
$currency = "huf";
$description = "20% előleg Mobil Barber";

printf($productName);


// Set API key 
StripeStripe::setApiKey(STRIPE_API_KEY);

$response = array(
    'status' => 0,
    'error' => array(
        'message' => 'Invalid Request!'
    )
);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $input = file_get_contents('php://input');
    $request = json_decode($input);
}

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode($response);
    exit;
}


if (!empty($request->createCheckoutSession)) {
    printf($productName);

    // Convert product price to cent 
    $stripeAmount = round($productPrice * 100, 2);

    // Create new Checkout Session for the order 
    try {
        printf($productName);
        $checkout_session = StripeCheckoutSession::create([
            'line_items' => [[
                'price_data' => [
                    'currency' => $currency,
                    'unit_amount' => $productPrice,
                    'product_data' => [
                        'name' => $productName,
                        'description' => $description,
                    ],
                ],
                'quantity' => 1,
            ]],
            'mode' => 'payment',
            'success_url' => STRIPE_SUCCESS_URL . '?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url' => STRIPE_CANCEL_URL,
        ]);
    } catch (Exception $e) {
        $api_error = $e->getMessage();
    }

    if (empty($api_error) && $checkout_session) {
        $response = array(
            'status' => 1,
            'message' => 'Checkout Session created successfully!',
            'sessionId' => $checkout_session->id
        );
    } else {
        $response = array(
            'status' => 0,
            'error' => array(
                'message' => 'Checkout Session creation failed! ' . $api_error
            )
        );
    }
}

// Return response 
echo json_encode($response);

When I print $chosenService and $productName variables outside the “if (!empty($request->createCheckoutSession)) {…}” condition, I get the parameters, so they are not NULL. But inside the condition I do not get anything back, neither NULL (does this mean that the $request is empty?). I even checked the Logs in Stripe dashboard, this is the err message there:

“parameter_missing – line_items[0][price_data][product_data][name]
Looks like you are missing the name field tied to a given line item’s product_data.

This field is required in that it contains the name that will show up on associated invoice line item descriptions.”

I would be really grateful, if someone could help me with this. Thank you in advance.

How to expand and collapse the table rows in plane react js. Show only one row if the description of the row is multiple and show the expand button

I am working on the table content which has 5 rows . few rows content description is same so I need to show only one row in this case and give expan button. when expand button is clicked it should show all the rows which has the same associated description. I am pasting the screenshot which I got as output .

In the above screenshot I’ve got the “-” button for all the rows which has same description. but I need only one “-“(collapse) button for “paytm” and one “-“button for “Paypal”. and when they are clicked only one paytm, PayPal should be displayed.

     let rows = [
          {
            id: { value: '' },
            description: { value: 'Paytm' },       
            DueDate: { value: '04/03/2020' },  
          },
          {
            id: { value: '' },
            description: { value: 'paypal' }, 
            DueDate: { value: '04/04/2021' }
          },
          {
            id: { value: '' },
            description: { value: 'paypal' }, 
            DueDate: { value: '04/03/2020' }
          },
          {
            id: { value: '' },
            description: { value: 'Paytm' },
            DueDate: { value: '04/03/2021' }
          },
          {
            id: { value: '' },
            description: { value: 'Gpay' }, 
            DueDate: { value: '04/03/2020' }
          },
        ];

I am showing the table based on the lasted date and check if there exists any multiple same descriptions and putting them all in one object.

    const descriptionSortedArray = rows.reduce((acc, current) => {
          acc[current.description.value] = [
            ...(acc[current.description.value] || []),
            current,
          ];
          return acc;
        }, {});
    
        console.log(descriptionSortedArray);

and transforming the object based on latest date

     const transformedRows = Object.keys(descriptionSortedArray).reduce(
          (acc, current) => {
            acc[current] = sortRowsByDate(descriptionSortedArray[current]);
            return acc;
          },
          {}
        );
        // console.log(Object.keys(descriptionSortedArray));
        console.log({ transformedRows });

and getting the key values for them by using object.keys and mapping over them.

    x.[paytm:[], Gpay:[], PayPal :[]];

based on the inner array key length I am showing button (expand and collapse)if
x[paytm]>1 ?show button: without button

code is below

    import React, { Component } from 'react';
    import './style.css';
    
    export default class App extends React.Component {
      render() {
        let rows = [
          {
            id: { value: '' },
            description: { value: 'Paytm' },       
            DueDate: { value: '04/03/2020' },  
          },
          {
            id: { value: '' },
            description: { value: 'paypal' }, 
            DueDate: { value: '04/04/2021' }
          },
          {
            id: { value: '' },
            description: { value: 'paypal' }, 
            DueDate: { value: '04/03/2020' }
          },
          {
            id: { value: '' },
            description: { value: 'Paytm' },
            DueDate: { value: '04/03/2021' }
          },
          {
            id: { value: '' },
            description: { value: 'Gpay' }, 
            DueDate: { value: '04/03/2020' }
          },
        ];
    
        const descriptionSortedArray = rows.reduce((acc, current) => {
          acc[current.description.value] = [
            ...(acc[current.description.value] || []),
            current,
          ];
          return acc;
        }, {});
    
        console.log(descriptionSortedArray);
    
        const sortRowsByDate = (rows) =>
          rows.sort(
            (a, b) => new Date(b.DueDate.value) - new Date(a.DueDate.value)
          );
    
        const transformedRows = Object.keys(descriptionSortedArray).reduce(
          (acc, current) => {
            acc[current] = sortRowsByDate(descriptionSortedArray[current]);
            return acc;
          },
          {}
        );
        // console.log(Object.keys(descriptionSortedArray));
        console.log({ transformedRows });
        
    
        return (
          <div>
            <table>
              <tr>
                <th>id</th>
                <th>description</th>
                <th>duedate</th>
                <th></th>
               
              </tr>
              {Object.keys(transformedRows).map((rowKey) => {
                // console.log("rowKey===", rowKey)
                //   console.log(transformedRows[rowKey])
                return (
                  <tbody>
                    {transformedRows[rowKey].length > 1
                      ? transformedRows[rowKey].map((obj) => (
                          <tr>
                            <td>{obj.id.value}</td>
                            <td>{obj.description.value}</td>  
                            <td>{obj.DueDate.value}</td>
                            <td>{<button>-</button>}</td>
                                                  </tr>
                        ))
                      : transformedRows[rowKey].map((obj) => (
                          <tr>
                            <td>{obj.id.value}</td>
                            <td>{obj.description.value}</td> 
                            <td>{obj.DueDate.value}</td>
                            <td></td>
                          </tr>
                        ))}
                  </tbody>
                );
              })}
            </table>
          </div>
        );
      }
    }

Please help in this. I need to show only one collapse button for the rows having same description(paytm is repeated show them only in one row give “expand” and “collapse” button). when even button is clicked it should be toggled. Please help

Are there alternative ways to send HTML elements through Cloud Firestore (using VueJS)

I’m making a discussion board website in VueJS, and one of the features I am making is to reply to comments. I want to have a little link/button that says “-Replying to post no. 3” for example. And when you click that link/button, the page will scroll up to the comment.

This is all easy stuff to do, I just make sure to select the comment div that is being replied to with

comm = document.querySelectorAll(".comment")

then when you click the button to see the replied comment, I run

this.comm.scrollIntoView({
   block: 'start',
   behavior: 'smooth',
   inline: 'start'
});

This all works fine for me, the problem is that I’m trying to use firebase to store my data for the comment objects. Right now I create a comment object like so:

var tempCommentObj = {
   commentName: this.name,
   commentReply: "-Replying to post no." + this.cArr.commentID,
   commentText: this.text,

   //more declarations
   commentReplyDiv: commR //commR being the comment element in question
   }

Then I push it into the comment array like this
this.actualArr.push(tempCommentObj);

So I want to have an HTML element as an item in my object so I can scroll up to it later when I press the button. However, firebase doesn’t let you store Elements, only strings, numbers, objects, dates etc. but no Elements

So I’ve tried to stringify with String() the element so I can store it as a string on the database, then unstringify it later when I want to press the button. And I actually do get back the right thing

<div class="comment" data-v-133ed8df>...</div>
But it’s just a copy of the element and not the real element, so when I try to scrollIntoView it doesnt do anything.

There has to be a better way of doing this, I would appreciate someone’s knowledge

(I have also tried getting the y position of the element using getBoundingClientRect() and doing it that way, but for some reason, it would never work, and the further down the page, the more negative the y would get. Maybe that’s the smarter way of doing this but I couldnt get it to work with)

I’m creating a quiz with 5 random questions (out of an array with 20). I want to assign a picture to every possible question

I’m creating a quiz with 5 random questions (out of an array of 20). I want to assign a picture to every possible question. The way I did that was using switch statements but that produces too much code as I have 20 questions. Is there another way to achieve this by using less code?

Here is the code I’m using:

const assignPictures = (value, questionID) => {

const addPicture = document.createElement("div");

 addPicture.setAttribute("class","imagesInQuestion")

  switch(true){
     
   case value === Array[0]:

      addPicture.innerHTML = `
   <img class="inlineImages" src ="/Images/Image.png">              
`
      break;
  
   case value === Array[1]:

      addPicture.innerHTML = `
      <img class="inlineImages" src ="/Images/Image2.png">              
   `
      break;

.....

how to sort array of objects by condition javascript

I have array of objects with properties.

I would like to sort by status, that is
15, 17 then 16 at last in javascript

For a array of objects , status having value 16

should be placed at last and rest should sort by ascending as the expected output.

How to do in javascript

var result = arrobj.filter(e=>e.details.status !== 16).sort(a, b) => a.status - b.status;

var arrobj = [
  {
    "id":1,
    "name": 'xyz',
    "details": {
    "job": 'fulltime',
    "status": 15
    }
  },
  { 
    "id":2,
    "name": 'abc',
    "details": {
    "job": 'partime',
    "status": 16
    }
  },
  { 
    "id":3,
    "name": 'zen',
    "details": {
    "job": 'fulltime',
    "status": 17
    }
  },
  { 
   "id":5,
    "name": 'abu',
    "details": {
    "job": 'fulltime',
    "status": 16
    }
  },
{ 
   "id":7,
    "name": 'john',
    "details": {
    "job": 'parttime',
    "status": 15
    }
  },
 { 
   "id":10,
    "name": 'jocob',
    "details": {
    "job": 'fulltime',
    "status": 17
    }
  }
]

Expected Output

[
  {
    "id":1,
    "name": 'xyz',
    "details": {
    "job": 'fulltime',
    "status": 15
    }
  },
 { 
   "id":7,
    "name": 'john',
    "details": {
    "job": 'parttime',
    "status": 15
    }
  },
  { 
    "id":3,
    "name": 'zen',
    "details": {
    "job": 'fulltime',
    "status": 17
    }
  },
 { 
   "id":10,
    "name": 'jocob',
    "details": {
    "job": 'fulltime',
    "status": 17
    }
  },
  { 
    "id":2,
    "name": 'abc',
    "details": {
    "job": 'partime',
    "status": 16
    }
  },
  { 
   "id":5,
    "name": 'abu',
    "details": {
    "job": 'fulltime',
    "status": 16
    }
  }
]


Does this.setState really make component re-render?

something about this.setState in class components is confusing me. in react docs, i read that this.setState may be asynchronous in react docs. im okay with this and i tested it with logging the updated value after this.setState. but it is really confusing me: when we call this.setState, react calls render method of the class to re-render the ui. but this.setState is asynchronous and it means that first render method will be called and ui will be re-rendered by react, then the value in the state will be changed! so how does component show us the updated value? i dont… am i thinking right?
thanks for helping.

How to append a div inside a div?

   $.each(v.Modifiers, function (_k, _v) {
      $modifierDiv.append(
        `<div class="col-xs-12 cart-modifier" style="padding: 0;" data-id="${_v.ModifierOptionID}">
          <p class="text-muted" style="padding: 5px; margin: 0; line-height: 14px;">
            ${_v.ModifierOption.Name}
          </p>
        </div>`
      );
    });

$(“.cart-items-right”).find(‘ul’).append(

${$modifierDiv}

);

The ${$modifierDiv} returns me [Object Object]. Pleasse help thanks.

multiple asynchronous post request with files in nodejs

I’ve tried to send a bunch of post requests with file upload in nodejs.
using axios.post, I could make a single request easily. But I got an error when trying send multiple asynchronous requests.

Based on the axios document, it uses axios.all([ axios.get(), axios.get(), …]) to make async requests at time.

If I sent my code, the error says:

“Error: Request failed with status code 500 ~ “

. This error is the same when I send a request without file upload. So I guess my code doesn’t attach a file when I send async request.

Please advise me what I am missing.

My code is below:

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('files', fs.createReadStream('./liscense.jpg'));

var config = {
  method: 'post',
  url: 'https://domainname/scan/id',
  headers: { 
    ...data.getHeaders()
  },
  data : data
};

axios
.all([axios(config), axios(config)])
.then(
    axios.spread((res1, res2) => {
        console.log(res1.data, res2.data);
    })
)
.catch((error) => {
  console.log(error);
});

convert template literal to retrieve object’s value without eval

// declared read-only variable:
const support = {
        arr: {
            ins: ['g3', 'g5', 'g7', 'g10',
                'g12', 'g13', 'g14', 'g15'
            ]
        }
    },
// object destructuring for easy to call:
{ arr: { ins: supE1range } } = support;

and a function to dynamically change between sup and 1 in supE1range object:

function autoSelect(currClass, currElite) {
    let setClass = '';
    switch (currClass) {
        case 'support':
            setClass = 'sup';
            break;
    }
    let setObj = `${setClass}E${currElite}range`;
    console.log(eval(setObj));
}
autoSelect('support', 1);

as you can see eval(setObj) will get supE1range‘s value because the string is match to the object name.

and now how to accomplish that without eval?
I’ve searching related questions/answers but doesn’t satisfy want i need.
umm.. don’t mind about ‘dynamically change’ because it’s just part of the code that is unnecessary to put here

Is this javascript frontend, NodeJS backend scenario viable to work?

I have a Domain-A which is static site built on netlify to provide shopping cart facilities.

I have a Domain-B server backend running a payment on Node.JS, and processing Auth Services via passport.js.

As a static site on Netlify this Domain-A cannot provide any backend services. The user sees this domain’s web pages, selects products, and eventually presses a buy button. This button invokes JS code running in the browser, sending an AJAX /login to Domain-B. It successfully logs in. It returns a connect.sid cookie to Domain-A with SameSite:none, Secure:true. I can see the cookie with Chrome Debugger.

After a successful login return from Domain-B, Domain-A now sends an AJAX GET to Domain-B requesting seller and payment information. But the GET always fails with a 403 “User Not Logged In”.

The AJAX GET includes

crossDomain: true,
headers: { 
    "Content-Type": "text/plain",
    "withCredentials": true
},

The Content-Type is to make it a CORS Simple Get and avoid Preflight issues, the withCredentials to make sure the cookie is included with the GET. I tried using a POST but it seems to always trigger Preflight processing which creates a lot of other complexities.

My basic question is, should I be able to do this, login and perform a GET from browser code of the Domain-A static site, to a NodeJS server on Domain-B? OR, must I get off Netlify and put it onto something like DigitalOcean where Domain-A has a backend which can login and get or post to Domain-B?

Is there sample code somewhere where I can copy the structure to my scenario? Thx.

How can I get the “name” of an object in a set of objects? Javascript

I have the following set of objects:

Variable {
  dataValues: {
    nombre: 'y',
    nombreAtributo: 'Descripción de valor 2',
    dato: '123',
    idUnidad: 1,
    Unidad: '(1,Lead)',
    UnidadMedida: UnidadMedida {
      dataValues: [Object],
      _previousDataValues: [Object],
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  },
Variable {
  dataValues: {
    nombre: 'z',
    nombreAtributo: 'Descripción de valor 3',
    dato: '123',
    idUnidad: 1,
    Unidad: '(1,Lead)',
    UnidadMedida: UnidadMedida {
      dataValues: [Object],
      _previousDataValues: [Object],
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  },
Historico {
  dataValues: { anio: 2022, valor: '13284', fuente: 'http://tanya.biz' },

Sorry for the vague question, but is there a way to obtain the “Variable {..}”?
This is because I want to be able to differentiate between the objects of type “Variable” and the objects with type “Historico”. As you can see, the values inside them may vary, so I want to implement a dynamical way to obtain them but I don’t know how to do it.

Why my reaction role command is not giving roles?

I have been messing around with this reaction role command, and it is meant to send embed, react to it, and give reaction roles. It does send embed and reacts to it, but it wont give any roles?

I would appreciate very much if someone could help me with this struggling, im not going to give up with this.

Error that i get:

                                                                    ^

TypeError: Cannot read properties of undefined (reading 'then')
    at Client.<anonymous> (C:UsersPauli.SalminenDesktopDiscordBotPRojectsreactionrolescommandsreactionrole.js:63:69)```

----------------------------------------------------------------------
Reactionrole.js:

```const { MessageEmbed, Role } = require('discord.js')


module.exports = {
    name: 'reactionrole',
    description: "Sends Embed with reactionrole!",
    async execute(message, args, Discord, kaoru) {
        const { MessageEmbed } = require('discord.js');
        


        //Define roles and emojis
        const FemaleRole =  message.guild.roles.cache.get('Female');
        const MaleRole = message.guild.roles.cache.get('Male');

        const emoji1 = '♀️';
        const emoji2 = '♂️';


        //Embed
        
            let embed = new MessageEmbed()
                .setColor("#FF6BDB")
                .setTitle(" <:pink_sakura:926036002932416542> Choose Gender <:pink_sakura:926036002932416542> ")
               
                .addFields(
                    {
                        name: "————————————",
                        value: "᲼᲼",
                    },
                    {   name: "᲼᲼᲼᲼♀️ Female ♀️n᲼᲼᲼᲼♂️   Male   ♂️",
                        value: "᲼᲼",
                    },

                {
                        name: "————————————",
                        value: "᲼᲼",
                }
                   
                )
                


        //sends embed and reacts

        message.channel.send({ embeds:  })
            .then(m => {
                m.react(`${emoji1}`);
                m.react(`${emoji2}`);
             });
            
            
    
      
     //Gives roles
     kaoru.on('messageReactionAdd', async (reaction, user) => {
        if (reaction.message.partial) await reaction.message.fetch();
        if (reaction.partial) await reaction.fetch();
        if (user.bot) return;
        if (!reaction.message.guild) return;
      
            if (reaction.emoji.name === emoji1) {
                await reaction.message.guild.members.cache.get(user).then(member => {
                    member.roles.add(FemaleRole);
            })
            if (reaction.emoji.name === emoji2) {
                await message.guild.members.cache.get(user).then(member => {
                    member.roles.add(MaleRole);
          
                })
            } else {
                return;
            }

        
      
    

    kaoru.on('messageReactionRemove', async (reaction, user) => {
        if (reaction.message.partial) await reaction.message.fetch();
        if (reaction.partial) await reaction.fetch();
        if (user.bot) return;
        if (!reaction.message.guild) return;

            if (reaction.emoji.name === emoji1) {
                await reaction.message.guild.members.cache.get(user).roles.remove(FemaleRole)
            }
            if (reaction.emoji.name === emoji2) {
                await reaction.message.guild.members.cache.get(user).roles.remove(MaleRole)
           
    
            }
    }

    


    )}
})

}
}