How to integrate razorpay payment gateway in Next.Js App?

I tried to integrate razorpay gateway but there is some confusion about it so plz help me I can integrate it.

import style from '../styles/Cart.module.css';
import Image from 'next/image';
import { useDispatch,useSelector } from 'react-redux';
import { useEffect } from "react";
import { useState } from 'react/cjs/react.development';

const Cart = () => {

how to razorpay payment gateway integrate

const [open,setOpen] = useState(false)
const [cash,setCash] = useState(false)
const dispatch =  useDispatch();
const cart = useSelector((state)=> state.cart);
const router = useRouter();
 return (
    <div className={style.container}>
        <div className={style.left}>
            <table className={style.table}>
            <tbody>
                <tr className={style.trTitle}> 
                <th>Product</th>
                <th>Name</th>
                <th>Extra</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total</th>
                </tr>
                </tbody>
                <tbody>
                {
                    cart.products.map((product) =>(
                <tr className={style.tr} key={product._id}>
                <td>
                    <div className={style.imgContainer}>
                        <Image src={product.img} alt='' layout='fill' 
                   objectFit='cover' />
                    </div>
                </td>
                <td>
                    <span className={style.name}>{product.title}</span>

                </td>

                <td>
                    <span className={style.extras}>
                    {
                        product.extras.map((extra)=>(
                            <span key={extra._id}>{extra.text}, </span>
                        ))
                    }
                    </span>
                </td>
                <td>
                    <span className={style.price}>${product.price}</span>
                </td>
                <td>
                    <span className={style.quantity}>{product.quantity}</span>
                </td>
                <td>
                    <span className={style.total}>${product.price * 
                  product.quantity}.      </span>
                </td>

                </tr>
                ))}
                </tbody>
            </table>
        </div>
        

here is the cart container where I want to show Razorpay gateway.

        <div className={style.right}>
            <div className={style.wrapper}>
                <h2 className={style.title}>CART TOTAL</h2>

                <div className={style.totalText}>
                    <b className={style.totalTextTitle}>Subtotal: </b> ${cart.total}
                </div>
                <div className={style.totalText}>
                    <b className={style.totalTextTitle}>Discount:</b> $0.00
                </div>
                <div className={style.totalText}>
                    <b className={style.totalTextTitle}>Total:</b> ${cart.total}
                </div>

I want to add here Razorpay gateway button below the cash on the delivery button

                {open ? (
            <div className={style.paymentgateway}>
            <button className={style.payButton} onClick={()=>setCash(true)}>CASH ON 
             DELIVERY</button>
              </div>
             )
              }

              

how to integrate Razorpay payment gateway on this jsx page in next.js

export default Cart

TextInput not focus on current touch in react-native

I have a simple TextInput like this

 const text =
    'Fusce id elit ut metus mattis fringilla. Ut accumsan, lacus vel rhoncus finibus, turpis massa euismod sapien, vitae ultrices odio tellus blandit ligula. Curabitur posuere turpis eget ipsum rutrum, sit amet ornare nibh cursus. Quisque commodo sapien et erat suscipit, ut lacinia mi blandit. In malesuada volutpat est pulvinar fermentum. Duis faucibus vel lorem et aliquet. Phasellus pharetra mattis massa, et posuere magna ultricies a. Nunc varius mollis vehicula. Nunc ut cursus mauris. Morbi et sem non leo imperdiet viverra non ac eros. Fusce fringilla molestie nisi, eget vulputate mauris maximus efficitur. Cras tortor libero, commodo et ante eu, fringilla lobortis turpis. Maecenas fermentum ligula ut erat feugiat cursus. Praesent blandit sagittis turpis ac egestas. Nunc non dolor ipsum. Phasellus vitae nisi eu justo ullamcorper ultricies efficitur in nunc.Nunc cursus justo neque, nec euismod est maximus quis. Aliquam scelerisque nunc dapibus, egestas orci vitae, ullamcorper tortor. Donec eget massa in felis placerat volutpat. Curabitur et erat non libero ultricies feugiat ornare vel erat. Quisque maximus dignissim arcu id iaculis. In aliquam rhoncus suscipit. Praesent ac lectus eget turpis pulvinar tempus.Ut hendrerit consequat luctus. Etiam porta arcu id erat condimentum scelerisque. Curabitur blandit nunc in sapien viverra sodales. Nullam tristique consequat mauris, vitae iaculis purus sagittis ac. Maecenas blandit enim ex. Sed et venenatis nulla. In nisl velit, vulputate a tempor nec, volutpat ut libero. Mauris vitae interdum magna, dapibus sollicitudin libero. Maecenas consequat mi magna, et dignissim est iaculis quis. Nullam pellentesque, neque quis efficitur semper, leo neque rutrum nulla, id malesuada enim tellus sed purus.Quisque finibus diam purus, sit amet porta orci ornare sit amet. Sed at sapien vitae massa tempus luctus sed sed elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ut mauris in ante molestie efficitur. Morbi feugiat nulla nec nunc ornare, ac mattis augue bibendum. Pellentesque consequat purus ut lectus porta molestie. Maecenas sed semper dui. Quisque aliquet eu sem ac suscipit. Donec et lectus nulla. Maecenas quis orci eu erat porta porta.Praesent consequat elit et sem cursus, vitae consequat arcu finibus. In non purus elit. Cras vehicula lacus sem, id blandit nisi auctor in. Etiam quis ipsum leo. Aliquam tincidunt purus nec feugiat feugiat. Vivamus suscipit eu purus eu euismod. Aliquam volutpat cursus lacus in ultrices. Curabitur at feugiat urna. Duis laoreet libero eu facilisis vehicula. Mauris ullamcorper, nibh et lacinia posuere, justo tellus sodales quam, at hendrerit ligula justo sed nunc. Cras ut elit malesuada, tempor arcu non, dignissim magna. Proin eget velit ultricies, facilisis nisl non, commodo leo.Vestibulum tincidunt, orci a malesuada scelerisque, neque justo dictum tellus, sed tincidunt arcu enim ut mi. Fusce sit amet urna sit amet libero ullamcorper molestie et ac risus. Praesent non sagittis quam. Integer non tellus vitae nisi scelerisque ullamcorper. Etiam lorem tellus, ultricies eu erat sit amet, laoreet condimentum turpis. Mauris eu magna interdum, dignissim metus facilisis, ultrices nisl. Donec pellentesque vestibulum nibh, vel vestibulum quam aliquam eu. Etiam convallis, mauris id efficitur congue, felis leo elementum augue, eget fringilla dui sapien nec massa. In non mauris nec eros mollis luctus. Integer in accumsan est. Sed in justo justo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin et erat lorem. Pellentesque vehicula nunc ut luctus aliquet.Curabitur nulla tortor, feugiat euismod sem id, interdum venenatis velit. Nam ut urna urna. Mauris sed condimentum nisl. Cras volutpat, velit vitae sodales posuere, diam risus laoreet ipsum, vel commodo tellus nisi in dolor. Etiam auctor malesuada velit sed posuere. Proin sed justo diam. Sed id ante enim. Curabitur sit amet dui at sapien cursus aliquet.Suspendisse blandit risus justo, eget ornare augue hendrerit id. Nulla facilisi. Curabitur aliquet magna eros, nec accumsan erat suscipit quis. Etiam facilisis, felis nec feugiat aliquam, erat dui posuere erat, at vehicula turpis ligula vel mi. Curabitur pretium, nulla at porta faucibus, velit augue finibus sapien, eget sagittis turpis orci ut nulla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum vitae convallis ligula. Duis bibendum quam vitae vehicula lacinia. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In commodo mi ipsum, in sollicitudin felis semper quis. Mauris aliquam leo at eros luctus, ac faucibus ligula accumsan. Vestibulum ac ultrices ante. Cras ac justo felis. Vivamus ultrices porta libero. Nam tellus erat, porta a neque non, finibus placerat erat. Vivamus eget nisl euismod, hendrerit tortor semper, eleifend orci';
  return (
    <ScrollView style={{flex: 1}}>
      <TextInput
        placeholder="Input"
        style={{fontSize: 50}}
        value={text}
        multiline
      />
    </ScrollView>
  );

But problem is, whenever.i click to the textInput on android, it will focus on the lastest, not where i click, it only happen on android , please help, thank you a lots

Here is the gif show problem i’m facing

Please help, how can i just focus on where i click on android???

enter image description here

How to write if else statement in reactJS when using useEffect?

Following is the code I’m using to return the Plotly graph, What I need to do in here is I need to return a message or different layout when the graph data is empty or there is nothing to show on the graph. use a default content like no data available if no data for charts. How do I do that?

import React, { useEffect } from "react";
import Plot from "react-plotly.js";
import PropTypes from "prop-types";

let dataArray;
let index;
let obj;
function PlotlyStackedChart({ labels, data, xTitle, yTitle, mainTitle, preHeading }) {
  useEffect(() => {
    dataArray = [];
    for (index = 0; index < data.length; index += 1) {
      obj = {
        x: labels,
        y: data[index].data,
        type: "bar",
        name: data[index].name,
      };
      dataArray.push(obj);
    }
  }, [data]);
  return (
    <>
      <Plot
        data={dataArray}
        layout={{
          barmode: "stack",
          autosize: true,
          title: {
            text: preHeading + mainTitle,
            y: 0.9,
          },
          margin: {
            t: 225,
          },
          xaxis: {
            // all "layout.xaxis" attributes: #layout-xaxis
            title: {
              text: xTitle,
              font: {
                family: "Arial Black",
              },
            }, // more about "layout.xaxis.title": #layout-xaxis-title
            // dtick: 1,
          },
          yaxis: {
            // all "layout.yaxis" attributes: #layout-yaxis
            title: {
              text: yTitle,
              font: {
                family: "Arial Black",
              },
            }, // more about "layout.yaxis.title": #layout-yaxis-title
          },
          font: {
            // family: "Courier New, monospace",
            size: 12,
            color: "#7f7f7f",
          },
          legend: {
            bgcolor: "transparent",
            x: 0,
            y: 1.4,
            xanchor: "auto",
            traceorder: "normal",
            orientation: "h",
          },
          marker: { size: 40 },
        }}
        useResizeHandler
        style={{ width: "100%", height: 600 }}
      />
    </>
  );
}

export default PlotlyStackedChart;

PlotlyStackedChart.defaultProps = {
  xTitle: "",
  yTitle: "",
  mainTitle: "",
  preHeading: "",
};

// Typechecking props for the MDDatePicker
PlotlyStackedChart.propTypes = {
  labels: PropTypes.oneOfType([PropTypes.string, PropTypes.array]).isRequired,
  xTitle: PropTypes.string,
  yTitle: PropTypes.string,
  mainTitle: PropTypes.string,
  preHeading: PropTypes.string,
  data: PropTypes.oneOfType([PropTypes.string, PropTypes.array, PropTypes.object]).isRequired,
};

explaining further, If there is no data to plot in the graph I want to return the following code else the current one which retrieves the data and plot in the graph.

return {
    "layout": {
        "xaxis": {
            "visible": false
        },
        "yaxis": {
            "visible": false
        },
        "annotations": [
            {
                "text": "No matching data found",
                "xref": "paper",
                "yref": "paper",
                "showarrow": false,
                "font": {
                    "size": 28
                }
            }
        ]
    }
}

Confusion related to Symbol.toprimitive method in js

In javascript, there is a symbolic property known as Symbol.toprimitive, which have function value, am I right?

If so, then in this method, the first word (ie. Symbol) is an system symbol?

And when we call this method, is there a formation of temporary object as we are creating property for a value that is primitive (symbol), of which value is an method?

And third confusion is in this method (ie. [Symbol.toprimitive] (hint), how the parameter hint knowns that hint should be “string” or “number” or “default” ?

Thanks for your valuable answer 🙂

Change the icon by changing the API data

I want to make a web with the subject of weather. I got to the point in the construction process that the icon should change with the change of weather.

    let shiftIcon = () => {

        let icon = "";
        let iconText = data.date[0].weather.code;

        if (iconText == 600) {
            icon = "https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
            return (
                <img src={icon} />
            );
        } else {
            return null;
        }
    }
   <div className="col col-3">
     {shiftIcon()}
 </div>

And after writing this code, I got an error. Do you have a solution for this?

TypeError: undefined is not an object (evaluating ‘e.component’)

Sorry if the answer to this question seems obvious, but it’s the first time ever that I’ve tried to upload a vue.js application.

So, whenever I try to visit my website on a shared hosting account, I get the error TypeError: undefined is not an object (evaluating 'e.component') from my main.js file at VueDriver.component(Code+i.path.replace(///g,"fowardslash"),i.component). I used the command vue create <app-name>, and uploaded my dist folder contents to my cpanel under public_html after running npm run build:

enter image description here

main.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Router from './Router.vue'
import Index from './Index.vue'


const make=(VueDriver,Code,Config)=>{
  Config.forEach(i=>{
    VueDriver.component(`${Code}${i.path.replace(///g,"fowardslash")}`,i.component);
  })
  return VueDriver
}
make(Vue,secure.main.codes.website,[
  {path:'/',component:Index},
])

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Login },
  ]
})

new Vue({
  el: '#app',
  router: router,
  render: h => h(Router)
})

How to Get Field Name(Capability Name) from GetFilter Method of powerBi using JavaScript

We are creating Visuals using Power BI API Client(JavaScript).Once it is created I want to pre populate all selected Capabilities and filters in another view.I used Visual.getFilters() method to get all pre selected filters but in each item I am not getting the capability to which it belongs,Is there is any way to get capability name with each filter.
for example

I selected bellow properties for creating a visual

Visual Type = Funnel

Capabilities

1 Group = Group1

2 Values = value1

after saving this visual when we execute getFilters(),we are getting this two objects but it does not contains Capability names like Group/Values

can’t resolve getaddrinfo EAI_AGAIN error

I’m having this error after 20 min of running my NodeJS app, and it’s keeps appearing after that.. it’s hosted at AWS (EC2) I searched for getaddrinfo EAI_AGAIN errors, it’s probably caused by DNS issue, but i have no idea how to solve it.

WebSocket error: [object Object]
ErrorEvent {
  target:
   WebSocket {
     _events:
      [Object: null prototype] {
        message: [Function: incoming],
        disconnect: [Function],
        close: [Function: close],
        error: [Function] },
     _eventsCount: 4,
     _maxListeners: undefined,
     _binaryType: 'nodebuffer',
     _closeCode: 1006,
     _closeFrameReceived: false,
     _closeFrameSent: false,
     _closeMessage: '',
     _closeTimer: null,
     _extensions: {},
     _protocol: '',
     _readyState: 2,
     _receiver: null,
     _sender: null,
     _socket: null,
     _bufferedAmount: 0,
     _isServer: false,
     _redirects: 0,
     _url: 'wss://stream.binance.com:9443/ws/!bookTicker',
     _req: null },
  type: 'error',
  message:
   'getaddrinfo EAI_AGAIN stream.binance.com stream.binance.com:9443',
  error:
   { Error: getaddrinfo EAI_AGAIN stream.binance.com stream.binance.com:9443
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
     errno: 'EAI_AGAIN',
     code: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'stream.binance.com',
     host: 'stream.binance.com',
     port: '9443' } }

Why does my text disappear in javascript?

Here is my code

const p = document.getElementById("looper");
function shiftright() {
    let temp = new String();
    for(var i = 1; i < p.textContent.length - 1; i++)
    {
        temp[i] = p[i-1];
    }
    temp[0] = p.textContent[p.textContent.length-1];
    p.textContent = temp;
}
window.setInterval(shiftright, 1000);

Whenever I run it the text within the element disappears once the interval expires. I am trying to make the text loop around.

Displaying PDF created with HttpContext.Current.Response in a div in asp.net page

My requirement is generating a itextsharp pdf file in button_click event on the fly without saving it in Local disk and there should be no save dialogue . Once the PDF is created we have to display it inside a div tag within the same asp.net page in a small size.
Below is the code in which I am able to generate the PDF:

protected void Button2_Click(object sender, EventArgs e)
    {
        string PDFfileName = Path.GetFileNameWithoutExtension(fileName);
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename= " + 
        PDFfileName + ".pdf"); 
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Document pdfDoc = new Document(); PdfWriter.GetInstance(pdfDoc, 
        HttpContext.Current.Response.OutputStream); 
        pdfDoc.Open();
        pdfDoc.Close();
        HttpContext.Current.Response.Write(pdfDoc);
        HttpContext.Current.Response.End();
    }

Now the challenge which I am facing:

  1. The generated PDF is getting opened in entire page like redirection but the URL remains the same.(If we click back button of browser, it is going to the page where I clicked the button to generate pdf)
    2)I am not able to display the generated PDF inside the div as a small part.

Solution which I want is the same pdf which is generated without saving it in disk should directly appear inside div tag in middle of the page and also it should not show any save dialogue message.

Please help me.

Stuck on algorithmic string task in js [closed]

I need help on that string task for a intership program(i have already handed over the tasks),but i really stuck in the start of the task.
enter image description here

    const arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];

const getValue = (temp) => {
    for (i = 0; i < 10; i++) {
        if (temp === arr[i]) {
            return i;
        }
    }
    return;
}


const charToDigit = (digit) => {
    let index = digit - 48;
    return arr[index];
}

}
console.log(solve(“fiveplusfive”));

How can I prevent loading images from stuttering?

I want to indicate that the page is loading, but even the loading animation stutters because many scripts are already running.

Can i write the code to prioritize Animation over other actions?

Please understand that I cannot show the actual code.
That ‘s too much .

All I can say is that I am using React.

I tried animation in CSS, gif and svg.
All of theses are stutters.

How to parse duplicate data in a list of objects based on multiple keys having the same value, where one key has a value of an array of objects

As the title states, I am trying to store a list of duplicate objects based on specific key:value pairs being the same.

The goal is to parse the information and return a list of duplicate items. A duplicate item is when the ID , title, items are a match.
The main problem I’m having with this is that inside each object, one of the keys to compare is an array holding a list of objects as values.

How would you go about this problem, looping through an array of objects to determine if the items array are duplicate?

Below is just a small example of the JSON data.

Should return :
whole object of pk:”0002″ and pk”0003″ since they are duplicate. Should not return Object pk:”0001″ and pk “0004” since their array of items:[{}] are not equal.

My attempt can determine if the ID and titles are a match but I can’t get the items to match:

var data = [
{ pk: "0001", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, { title: "EXTRA", value: "55" }, ], }, 
{ pk: "0002", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
{ pk: "0003", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
{ pk: "0004", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
];


let duplicates = [];
data.forEach((el, i) => {
  data.forEach((element, index) => {
    if (i === index) return null;
    if (element.ID === el.ID && element.title === el.title) {
      if (!duplicates.includes(el)) {
        //Issue here -> I want to compare the array of items but im not sure how to ?
        //Attempt:
        // I think I understand that this is wrong due to the indexes not sure how you would find this ?

        // if (element.items[i] === el.items[i]) {
        //   duplicates.push(el);
        //   console.log("Test");
        // }

        duplicates.push(el);
      }
    }
  });
});
console.log("duplicates", duplicates);

Is it possible to execute code after responding on a Cloudflare Worker?

I am starting workig with Cloudflare and I a m facing one of my first challenges.

I have some cached data, that I retrieve once I get it requested via a ‘fetch’ event. I would like after responding to this fetch, update the cache data that was requested.

I get this data from a third party API.

The workflow would be the following.

  1. Get the request and respond with cthe old cached item
  2. Refresh the cache for the requested item afterwards

I was thinking about using a cron timers and filling up a queue of items to update, but I think this list will not be persisted.

The ideal way would be having some sort of custom event I can register and fire just before I return the response, so while I am returning the old cached data the refresh cache job is already executing.

My current code is working (2 is not implemented yet), and I am not posting code, because I just would like to know some theories about how could this refresh be done.

Thanks in advance!

Login in Cypress without hardcoding

I don’t know how to rewrite this syntax correctly, because I get an error like “Invalid left-hand side in assignment expression.”

Cypress.Commands.add('logintest', (env,username) => {
    env(staging) = cy.visit('link')
    env(live) = cy.visit('link') 

    username (userone =
      cy.get('input[name="Parameter.UserName"]').type('userone'),
      cy.get('input[name="Parameter.Password"]').type('password')
    )
})