React renders repeatedly on event

I’m using sockets in my website and there’s an event where one user can send a word to the server, which emits (art-addpic) an image URL corresponding to that word to everyone, but only the user with isArtist=true gets to respond to the event.
The artist’s page is supposed to update an existing list of image URLs (optionImages) with the received URL once. But when the event is received, all images in the list are replaced by the received URL. Furthermore, the component rendering the list of images ArtBoard is not re-rendered with updated URLs.
I’m new to React. Where am I going wrong?

I’ve checked the server and the event art-addpic is broadcasted only once.

Arena.js: (The webpage where this happens):

import React, { useEffect, useState } from "react";
import Leaderboard from "../comps/Leaderboard";
import { io } from "socket.io-client";
import Service from "../Service";
import DetBoard from "../comps/DetBoard";
import ArtBoard from "../comps/ArtBoard";
const username = "Nick"
const roomkey="abc"
let userid;
if(localStorage.getItem('userid')){
    userid = localStorage.getItem('userid')
}
else{
    userid = Service.makeid(5);
    localStorage.setItem('userid', userid);
}
function useForceUpdate(){
    const [value, setValue] = useState(0); // integer state
    return () => setValue(value => value + 1); // update the state to force render
}
// const [userid,setUserId] = 
const socket = io('http://localhost:3001', {query:"username="+username+"&roomkey="+roomkey+"&userid="+userid});
const Arena = (props)=>{
    const [isArtist, setIsArtist] = useState(false);
    const [focusImage, setFocusImage] = useState('https://i.imgur.com/61HsZCU.jpeg')
    const [players, setPlayers] = useState([]);
    const [optionImages, setOptionImages] = useState([
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg'
    ])
    useEffect(()=>{
        socket.on('connect',()=>{
            console.log("connected")
        })
        socket.on('players', (data)=>{
            data = JSON.parse(data)
            console.log(data)
            setPlayers(data)
        })
        socket.on('artist', (data)=>{
            if(data===userid){
                console.log('You are an artist, Mr White.')
                setIsArtist(true);
            }
            else{
                setIsArtist(false);
            }
        })    
        socket.on('art-addpic', (data)=>{
            data = JSON.parse(data)
            console.log(data)
            let tempOps =optionImages;
            tempOps.splice(0, 1);
            tempOps.push(data.url)
            console.log(tempOps)
            setOptionImages(tempOps);
        })
    }, [
        optionImages
    ]);
    if(isArtist){
        return(
            <div>
            <Leaderboard players={players}></Leaderboard>
            {/* <ArtBoard></ArtBoard> */}
            <ArtBoard socket={socket} focusImage={focusImage} optionImages={optionImages} setOptionImages={setOptionImages}/>         
        </div>
        );
    }
    else{
        return (
            <div>
            <Leaderboard players={players}></Leaderboard>
            {/* <ArtBoard></ArtBoard> */}
            <DetBoard socket={socket} focusImage={focusImage}/>         
        </div>
        );
    }
}
export default Arena;

How to always place upload field right side next to preview file in Dropzone?

Currently I have a customized dropzone that I styled on my own. However, after uploaded a file, I want the upload field is always right side next file preview, just like this:

enter image description here

But by the default dropzone always places the upload field left side to the file preview as in my current script below.

$(document).ready(function() {

  var previewNode = document.querySelector('.upload-thumbnail');
  previewNode.id = "";

  var previewTemplate = previewNode.parentNode.innerHTML;
  previewNode.parentNode.removeChild(previewNode);


  default_dz_option = {
    url: '/upload',
    method: "post",
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    thumbnailWidth: 80,
    thumbnailHeight: 80,
    timeout: 0,
    previewTemplate: previewTemplate,
    previewsContainer: '.thumbnail-container'
  };

  myDropzone = new Dropzone('#upload_field', default_dz_option);

});
.thumbnail-container {
  padding: 0 10px;
}

.upload-thumbnail {
  background: #E7F3FF;
  color: #1977F2;
  padding: 5px 16px 5px 7px;
  border-radius: 50px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-grow: 0;
  min-width: 100px;
  position: relative !important;
  margin-right: 8px;
  margin-bottom: 10px;
  position: relative;
}

.upload-thumbnail {
  font-size: 10px;
}

.upload-thumbnail a {
  font-size: 11px;
  text-decoration: none;
}

.upload-thumbnail span {
  font-size: 11px;
}

.upload-thumbnail .remove-thumbnail {
  transform: translateX(5px);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0-10/css/all.min.css" integrity="sha512-Pv1WJMqAtVgNNct5vhq+4cgkKinKpV1jCwSWD4am9CjwxsJSCkLWKcE/ZBqHnEE1mHs01c8B0GMvcn/pQ/yrog==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>

<div class="thumbnail-container" style="display: flex;flex-wrap: wrap;margin-top: 10px;position: relative;width: 600px;">
  <div class="upload-thumbnail" style="margin-right: 30px;">
    <div class="image">
      <i class="fa fa-paperclip" aria-hidden="true"></i>&nbsp;&nbsp;
      <a href="javascript:" class="image-name" data-dz-name></a href="javascript:">
    </div>
    <a href="javascript:" class="remove-thumbnail" data-dz-remove><i class="fas fa-times "></i></a>
  </div>
  <div class="" id="upload_field" style="width: 36px; height: 36px; border: 1px dashed; "> </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/min/dropzone.min.js" integrity="sha512-oQq8uth41D+gIH/NJvSJvVB85MFk1eWpMK6glnkg6I7EdMqC1XVkW7RxLheXwmFdG03qScCM7gKS/Cx3FYt7Tg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

How can I achieve that like in the picture? Thanks so much.

Sinon stub out module’s function from a middleware

Based on this question, I need to also make a test for a middleware which also uses the db-connection.js file. The middleware file will look like this:

const dbConnection = require('./db-connection.js')

module.exports = function (...args) {
   return async function (req, res, next) {
      // somethin' somethin' ...
      const dbClient = dbConnection.db
      const docs = await dbClient.collection('test').find()
 
      if (!docs) {
         return next(Boom.forbidden())
      }
   }
}

, the database connection file do not change, which is:

const MongoClient = require('mongodb').MongoClient
const dbName = 'test'
const url = process.env.MONGO_URL

const client = new MongoClient(url, { useNewUrlParser: true,
  useUnifiedTopology: true,
  bufferMaxEntries: 0 // dont buffer querys when not connected
})

const init = () => {
  return client.connect().then(() => {
    logger.info(`mongdb db:${dbName} connected`)

    const db = client.db(dbName)
  })
}

/**
 * @type {Connection}
 */
module.exports = {
  init,
  client,
  get db () {
    return client.db(dbName)
  }
}

How the middleware works is by passing list of strings (that strings is roles), I have to query to the database and check whether there is a record of each roles. If the record exists, I will return next(), while if the record does not exist, I will return next(Boom.forbidden()) (next function with a 403 status code from Boom module).

Given the details above, how does one make a test to test out the return value of the middleware if the record exists or not? This means I have to assert the next() and next(Boom.forbidden) to be exact.

How to use just 1 useState() for serveral states

I have a react component that uses several states which are initialized in the same way useState(false), is there a way to combine all these states into a single useState(false)

  const [loading, setLoading] = useState(false);
  const [fields, setFields] = useState(false);
  const [wrongImageType, setWrongImageType] = useState(false);
  const [aboutError, setAboutError] = useState(false);
  const [destinationError, setDestinationError] = useState(false)

how Variable assignment work in javascript?

class Node{
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

class SinglyLingkedList{
    constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    push(val){
        var newNode = new Node(val)
        if (this.head == null) {
            this.head = newNode;
            this.tail = this.head;
        } else{
            this.tail.next = newNode;
            this.tail = newNode;
        }
        
        this.length++;
        return this
    }

    reverse(){
        var node = this.head;
        this.head.next = null;
        this.tail = this.head;
        return node;
    }
}

var list = new SinglyLingkedList()
list.push("1")
list.push("2")
list.push("3")
list.reverse()

I’m new at programming. I’m pretty confused with my variable assignment in the reverse method, especially at

        var node = this.head;
        this.head.next = null;
        this.tail = this.head;
        return node;

Why return node is affected by this.head.next null? is not like what I expected
its return

Node : {val: '1', next: null}

not

Node : {val: '1', next: Node}

I wanted to know why it happened?

Props,State and CombineReducer in React JS

Given is an AuthenticationReducer:

import * as authenticationActions from "./AuthenticationAction";
//import * as managementActions from "./ManagementAction";

const initialState = {
  user: null,
  loginPending: false,
  showLoginDialog: false,
  showCreateUserDialog: false,
  showUpdateUserDialog: false
};
function authenticationReducer(state = {}, action) {
  console.log("Bin im Reducer" + action.type);

  switch (action.type) {
    case authenticationActions.SHOW_LOGIN_DIALOG:
      return {
        ...state,
        showLoginDialog: true,
        error: null,
      };

    case authenticationActions.HIDE_LOGIN_DIALOG:
      return {
        ...state,
        showLoginDialog: false,
        error: null,
      };
default:
  return state;
}
}

export default authenticationReducer;

The reducer works independently, but if I use combineReducer I cannot use the login-Dialog in UserSessionWidget any longer.

index.js

import thunk from 'redux-thunk'
import App from './App';
import reportWebVitals from './reportWebVitals';
import authenticationReducer from './redux/authentication/AuthenticationReducer'
import { combineReducers } from 'redux';

const initialState = {}
const middleware=[thunk]
const reducer = combineReducers({
  authenticationReducer: authenticationReducer
  
})
const store = createStore(reducer,initialState,applyMiddleware(...middleware))

UserSessionWidget

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import Button from "react-bootstrap/Button";
import Modal from "react-bootstrap/Modal";
import Form from "react-bootstrap/Form";
import * as authenticationActions from "../actions/AuthenticationAction";

const mapStateToProps = (state) => {
  return state;
};

class UserSessionWidget extends Component {
  constructor(props) {
    super(props);
    this.state = { userID: "", password: "" };
    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleShow(e) {
    e.preventDefault();
    /* this.setState({show: true}) */
    const { showLoginDialogAction } = this.props;
    showLoginDialogAction();
  }
  handleClose(e) {
    e.preventDefault();
    this.setState({ show: false });
    const { hideLoginDialogAction } = this.props;
    hideLoginDialogAction();
  }

  handleChange(e) {
    const { name, value } = e.target;
    this.setState({ [name]: value });

    console.log(JSON.stringify(this.state));
  }

  handleSubmit(e) {
    e.preventDefault();
    const { userID, password } = this.state;
    const { authenticateUserAction } = this.props;
    authenticateUserAction(userID, password);
    console.log("Pushed submit");
  }

  render() {
    var showDialog = this.props.showLoginDialog;
    if (showDialog == undefined) {
      showDialog = false;
    }

    return (
      <div>
        <Button variant="primary" onClick={this.handleShow}>
          Login
        </Button>
        <Modal show={showDialog} onHide={this.handleClose}>
          <Modal.Body>
            <Form>
              <Form.Label>userID</Form.Label>
              <Form.Control
                id="LoginUserIDInput"
                type="text"
                placeholder="User ID"
                name="userID"
                onChange={this.handleChange}
              />
              <br />

              <Form.Label>password</Form.Label>
              <Form.Control
                id="LoginPasswordInput"
                type="password"
                placeholder="Password"
                name="password"
                onChange={this.handleChange}
              />

              <Button
                variant="primary"
                type="submit"
                onClick={this.handleSubmit}
              >
                Submit
              </Button>
            </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleClose}>
              Close
            </Button>
          </Modal.Footer>
        </Modal>
      </div>
    );
  }
}

const mapDisaptchToProps = (dispatch) =>
  bindActionCreators(
    {
      showLoginDialogAction: authenticationActions.getShowLoginDialogAction,
      hideLoginDialogAction: authenticationActions.getHideLoginDialogAction,
      authenticateUserAction: authenticationActions.authenticateUser,
    },
    dispatch
  );
const ConnectedUserSessionsWidget = connect(
  mapStateToProps,
  mapDisaptchToProps
)(UserSessionWidget);

export default ConnectedUserSessionsWidget;

My App.js starts like this:

const mapStateToProps =state => {
  return state
}

question: It can be conjectured that the state in mapsStateToProps is not transferred. How should I change the mapStateToProps to use UserSessionWidget properly ? Or is the error anywhere else ?

How to Reload to same Page while sending a parameter?

I need to reload the page whenever different buttons are pressed, while sending a String to the same page so that on created() it takes that String and sends an HTTP Get into my Database.

Currently I have the following:

export default {
    data(){
        return{
            events: [],
            formData:{
                sportType: 'Ténis'
            }
        }
    },

    created(){
        //Do something here to get the value sent from the reloading
        axios.get(`http://localhost:8001/evento`, {headers: {sportType: this.formData.sportType}})
            .then((response)=>{
                this.events = response.events
            },(error) =>{
                console.log(error);
        });
    },
    pickSport(item){
                
    }

The function pickSport() is called whenever the buttons are pressed and each sends a value to this function that is a String. The idea now is to be able to reload the page when this function is called, while sending this item to the reloaded page, so I can update the value of sportType. I tried:

        pickDesporto(item){
            this.$router.push({
                path: '/betting',
                params: item
            });
        }

But with no success, since it keeps giving me a NavigationDuplicated error. How can I solve this?

How Do I change the color of webgl points?

This is the code I used to try to change the color of WebGL points:

I want to change the color of WebGL points when a user clicks the body element.
And FYI the shaders are compiling correctly.

The numbers in the color_obj object seem to be changing when I click on the screen. However, the WebGL colors don’t change. Can someone help me with this?

const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

gl.clearColor(0.3, 0.6, 0.7, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT || gl.DEPTH_BUFFER_BIT);

if (!gl) {
    throw new Error("WebGL not supported");
}

console.log("This is working");

const points = [
    1.0, 1.0, 0.0,
    1.0, -1.0, 0.0,
    -1.0, -1.0, 0.0,
    1.0, 1.0, 0.0,
    -1.0, -1.0, 0.0,
    -1.0, 1.0, 0.0
];

let color_obj = {
    color_1: 0.4,
    color_2: 0.7,
    color_3: 0.8,
    color_4: 0.0,
    color_5: 0.5,
}

let colors = [
    color_obj.color_1, color_obj.color_2, color_obj.color_3,
    color_obj.color_3, color_obj.color_1, color_obj.color_3,
    color_obj.color_4, color_obj.color_4, color_obj.color_4,
    color_obj.color_1, color_obj.color_2, color_obj.color_3,
    color_obj.color_4, color_obj.color_4, color_obj.color_4,
    color_obj.color_5, color_obj.color_5, color_obj.color_5
];

const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(points), gl.STATIC_DRAW);

const buffer_2 = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer_2);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW)

const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, `
precision mediump float;

attribute vec3 pos;
attribute vec3 rgb;
varying vec3 rgbColor;

void main() {
    rgbColor = rgb;
    gl_Position = vec4(pos, 1);
}
`);
gl.compileShader(vertexShader);

const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, `
precision mediump float;

varying vec3 rgbColor;

void main() {
    gl_FragColor = vec4(rgbColor, 1);
}
`);
gl.compileShader(fragmentShader);

const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);

const positionRef = gl.getAttribLocation(program, `pos`);
gl.enableVertexAttribArray(positionRef);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(positionRef, 3, gl.FLOAT, false, 0, 0);

const colorRef = gl.getAttribLocation(program, `rgb`);
gl.enableVertexAttribArray(colorRef);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer_2);
gl.vertexAttribPointer(colorRef, 3, gl.FLOAT, false, 0, 0);

gl.useProgram(program);

document.body.addEventListener("mouseup", () => {
    console.log("Body Clicked");
    color_obj.color_1 += 0.1;
    color_obj.color_2 += 0.1;
    color_obj.color_3 += 0.1;
    color_obj.color_4 += 0.1;
    color_obj.color_5 += 0.1;

    console.log(color_obj.color_1);
    console.log(color_obj.color_2);
    console.log(color_obj.color_3);
    console.log(color_obj.color_4);
    console.log(color_obj.color_5);
});

function animate() {
    requestAnimationFrame(animate);

    gl.drawArrays(gl.TRIANGLES, 0, 6);
}

requestAnimationFrame(animate);
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>WebGL</title>
    <style>
        canvas {
            position:fixed;
            width:100%;
            height:100%;
        }

        html, body {
            margin:0 !important;
            padding:0 !important;
            overflow:hidden;
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script src="app.js"></script>
</body>

</html>

How to pass the key used from JSON response objects in a map as a parameter for onclick() function in React?

I have tried to create a list of ‘League’ objects from the server, the user can click to create a league successfully, but to join a league the user will need to click the icon and the parameter will need to be sent to the joinLeague() function as the league.leagueId is required to join the league by the API:

LeagueList component:

 constructor(props) {
    super(props);
    this.state = {
        leagues: []
    };

    this.createLeague = this.createLeague.bind(this);

    this.joinLeague = this.joinLeague.bind(this);
}

 joinLeague() {
    const payload = {
        "username": localStorage.getItem("username"),
        "leagueId":
    };
    fetch(JOIN_LEAGUE_URL, {
        method: 'POST',
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": localStorage.getItem("token")
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then();
}

   render() {
        const {leagues} = this.state;

    const leagueList = leagues.map(league => {
        return <tr key={league.leagueId}>
            <td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td>
            <td>{league.playerCount}/10</td>
            <td>{league.matchesPerPlayer}</td>
            <td>{league.numberOfGamesPlayed}</td>
            <td>{league.totalGamesToBePlayed}</td>
            <i className="fas fa-plus" onClick={this.joinLeague}></i>
        </tr>
    });

}

In the joinLeague() function above you can see I am trying to create the payload but I need the leagueId from the as a parameter.

How can I accomplish this? I have tried {this.joinLeague.bind(league)} but it didn’t work, thanks.

React and Next postMessage communication CORS problem

I have two apps – CRA running on port 3000, and Next running on 3005.

In Next app I have simple message event listener:

  useEffect(() => {
    const handleMessage = (event: MessageEvent<{}>) =>
      console.log('Message event: ', event);

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

And I’ve set up headers in next.config.js:

const securityHeaders = [
  { key: 'Access-Control-Allow-Credentials', value: 'true' },
  { key: 'Access-Control-Allow-Origin', value: '*' },
  {
    key: 'Access-Control-Allow-Methods',
    value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
  },
  {
    key: 'Access-Control-Allow-Headers',
    value:
      'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
  },
];

const nextConfig = {
  async headers() {
    return [
      {
        // Apply these headers to all routes in your application.
        source: '/:path*',
        headers: securityHeaders,
      },
    ];
  },
};

module.exports = nextConfig;

In React app I’m calling postMessage through iframe tag like this:

export const Frame = () => {
  const frameRef = useRef<HTMLIFrameElement>(null);

  const handleFrameLoad = () => {
    frameRef?.current?.contentWindow?.postMessage('TEST');
  };

  return (
    <iframe
      src="http://localhost:3005"
      ref={frameRef}
      onLoad={handleFrameLoad}
      sandbox="allow-same-origin allow-scripts"
    />
  );
};

And I’m still receiving error below in CRA’s console.

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:3005').

Is there anything else that I can do to allow postMessage communication between two different local ports in NextJS?

Can you make a map based off address firebase?

I am trying to make a program that creates a google map based off the address given by user input. As i can not manually embed a link for each page, how can i make it so that when a user answers a form with the address I can take that address and make a google map. Do i have to convert the address to latitude and longitude and then do that?

await hitting timeout in jest unit test?

import { fs } from 'memfs';

describe('copyFolder()', () => {
  it('should work', async () => {
    await fs.promises.mkdir('/tmp/destination');
    console.log(fs.existsSync('/tmp/destination'));
  });
});

I’ve verified that fs.promises.mkdir('/tmp/destination') will return a promise and hence by having an await in front of it should be able to resolve it but seems like this is not the case for jest? it will just hit timeout instead?

Anyone has any clue about this?

Show wallet address after connecting Metamask with Web3.js

I got this code off github which allows you to connect to MetaMask using web3.js and also to make payment. I then modified it to

  1. Display a Connect Button when user is not logged in by checking if the content of an element is empty and if it is not empty, the connect button is hidden.
  2. Retrieve the connected wallet address which is in the element that hides the button.

I want the connected wallet to show up and hide the Connect button as soon as MetaMask is connected but it does not do that until i manually reload the page

Below is my code

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="https://unpkg.com/@metamask/legacy-web3@latest/dist/metamask.web3.min.js"></script>
  </head>
  <body>
    <div>
        
      <div id="selected-account"></div>
      <button class="pay-button">Pay</button>
      <div id="status"></div>
      <div id="accTabs"></div>
    </div>
    <script type="text/javascript">
      async function initWeb3() {
        if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        
        try {
            
          await ethereum.enable();
    window.location.reload();
          } catch (err) {
            $("#status").html("User denied account access", err);
          }
        } else if (window.web3) {
            
          return (window.web3 = new Web3(web3.currentProvider));
          
        } else {
          return $("#status").html("No Metamask (or other Web3 Provider) installed");
        }
      }
      
      selectedAccount = ethereum.selectedAddress;
  document.querySelector("#selected-account").textContent = selectedAccount;

      $(".pay-button").click(async () => {
        await initWeb3();
        // paymentAddress is where funds will be send to
        const paymentAddress = "0x192c96bfee59158441f26101b2db1af3b07feb40";
        const amountEth = "1";



        web3.eth.sendTransaction(
          {
            to: paymentAddress, 
          value: web3.toWei(amountEth, 'ether')
          },
          (err, transactionId) => {
            if (err) {
              console.log("Payment failed", err);
              $("#status").html("Payment failed");
            } else {
              console.log("Payment successful", transactionId);
              $("#status").html("Payment successful");
            }
          }
        );
      });
    </script>
    
    <script>
  if ($('#selected-account').text() == '') {
document.getElementById("accTabs").innerHTML = '<button onclick="initWeb3()">Connect Ethereum</button>';
} else {


}
     
</script>
  </body>
</html> 

Your help will be appreciated!

Thanks for your assistance.