Module bundler for frontend only

Can I use a module bundler for an existing apache/mysql/php backend app (running in docker)? Im adding React components just here and there in some pages. Currently I`m using Babel but I want to be able to add imports too.

Reading NFC tags in the browser

As I was working on an E-wallet system, my boss assigned me a job to allow our agents to be able to top-up the clients’ wallets by reading their NFC cards. The agents are using a web browser client to browse their CMS part of the System, I made that myself.
Is it possible to read NFC through the web browser?

I thought that wouldn’t be possible by writing a JavaScript code on an HTML page, but I imagine that this could be done by making a browser extension. However, I’m not sure if that’s the way to go. and what would be the next.

Insert javascript method inside html paragraph

<!DOCTYPE html>
<html>
<body>

<h2>My First JavaScript</h2>

<p id="demo"><script>Date()</script></p>    <!-- here I want to put the output of Date() method -->

</body>
</html> 

I know that I can do something like:

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

But I’d like to know if there’s a way to do that inside the paragraph directly.

Can I error handle await Promise.all with a try-catch block?

I have the following piece of code:

    const [groupedMeditations, meditationPreferences] = await Promise.all([
        getMeditationsByGroup(),
        getAllPreferences(),
    ]);

but currently errors are not handled in any way. Would it be correct to surround that piece of code with try-catch like this:

    try {
        const [groupedMeditations, meditationPreferences] = await Promise.all([
            getMeditationsByGroup(),
            getAllPreferences(),
        ]);
    } catch (error) {
        // error handle
    }

Get value from span to Django view

I have this javascript that gets longitude and latitude from a Google Map:

<script>
    // Get element references
    var confirmBtn = document.getElementById('confirmPosition');
    var onClickPositionView = document.getElementById('onClickPositionView');
    var latonIdlePositionView = document.getElementById('latOnIdlePositionView');
    var longonIdlePositionView = document.getElementById('longOnIdlePositionView');
  
    // Initialize locationPicker plugin
    var lp = new locationPicker('map', {
      setCurrentPosition: true, // You can omit this, defaults to true
    }, {
      zoom: 15 // You can set any google map options here, zoom defaults to 15
    });
    // Listen to map idle event, listening to idle event more accurate than listening to ondrag event
    google.maps.event.addListener(lp.map, 'idle', function (event) {
      // Get current location and show it in HTML
      var location = lp.getMarkerPosition();
      latOnIdlePositionView.innerHTML = location.lat;
      longOnIdlePositionView.innerHTML = location.lng;
    });
  </script>

This is the HTML I have for a user to define his or her location:

<form method="POST" action="{% url 'geolocate' %}">
{% csrf_token %}
    <div class="card-header">
        <div class="float-start">
        <h3 class="card-title">Me localiser</h3>
        </div>
    </div>
    <div class="card-body no-padding">
        <div id="map"></div>
        <p>Latitude: <span id="latOnIdlePositionView"></span> Longitude: <span id="longOnIdlePositionView" ></span></p>
    </div>
    <div class="card-footer text-end">
        <button type="submit" class="btn btn-primary">Mettre à jour</button>
    </div>
</form>

This is my view:

def geolocate(request):
    if request.method == 'POST':
        lat = request.POST.get('lat_kw')
        long = request.POST.get('long_kw')

        caccount = Account.objects.get(username=request.user.username)
        caccount.lat = lat
        caccount.long = long
        caccount.save()
        return redirect('monprofil')

What I want to do is to get the value form the spans latOnIdlePositionView and longOnIdlePositionView and put them in my view.

I know how to do this if I have data in an input field (using name), but I do not know how to do this using spans.

Javascript/React code – control/page won’t render in fileReader.onload

I have a react page and one of my inputs is a file upload. When loading, I want to read in the file (it’s JSON) and then show the file as a tree to allow my users to select nodes (rules) to run against another dataset. BUT, when I pick the JSON file and the ‘onload’ event handler actually fires off, the page just stops rendering, I get a blank screen. I’m not sure why, I can’t see any errors, but I AM IGNORANT with react and kinda new with javascript as well. So, this is quite likely just a dumb thing I’m doing. Can someone point me at what I’m doing wrong here?

    handleRules(event) {
        const ruleRdr = new FileReader();
        ruleRdr.onload = async (e) => {
            const rBuf = (e.target.result);
            const rData = JSON.parse(new TextDecoder().decode(rBuf));
            // the data is there, but it's not mapping into the tree...!?!?!?
            const tree = {
                name: "QA/QC Rules",
                id: 1,
                toggled: true,
                children: rData.map((wFlow, index) => ({
                    name: wFlow.WorkflowName,
                    id: index,
                    children: wFlow.Rules.map((rule, idx) => ({
                        name: rule.RuleName,
                        id: idx
                    }))
                }))
            };
            this.setState({ ruleData: rData, hasRules: true, treeData: tree });
        }
        ruleRdr.readAsArrayBuffer(event.target.files[0]);
    }

How to import multiple Images neatly in next/js?

The question is that I am having 10 images in my public folder and I want to use them in a component. Instead of writing

import imgurl1 from "../../public/celsius.gif";
import imgurl2 from "../../public/compass.gif";
import imgurl3 from "../../public/rain.gif";
.
.
.
import imgurl8 from "../../public/thermo.gif";
import imgurl9 from "../../public/sunset.gif";
import imgurl10 from "../../public/wind.gif";

the above code, I want to use something more neatly and clean code? Is there any way not to repeat the same line and import all of them?

I am assuming something like

import { imgurl1,imgurl2,...imgurl10, } from "../../public";

Date format using Javascript

How to get the formatted date from data result?

var obj = data.map(row => ({
     id: row[0],
     status: row[1],
     datepublished: row[2]
}));

This is the result when i didnt format the datepublished field

[
    {
        "id": 440937003,
        "status": "Not Available",
        "datepublished": "2022-03-27T16:00:00.000Z"
    }
]

var obj = data.map(row => ({
     id: row[0],
     status: row[1],
     datepublished: new Date(row[2].getTime() - (row[2].getTimezoneOffset() * 60000 )).toISOString().split("T")
}));

This is my current result data

[
    {
        "id": 440937003,
        "status": "Not Available",
        "datepublished": [
            "2022-03-28",
            "00:00:00.000Z"
        ]
    },
]

what I want result is

[
    {
        "id": 440937003,
        "status": "Not Available",
        "datepublished": "2022-03-28"
    },
]

Rendering UI with Utility module in single-spa

I am trying to render a UI component using in-browser utility module in single-spa, which I have created using create-single-spa command and selected in-browser module option. As there is no “single-spa-react” library comes with in-browser utility module which helps to render elements to dom, how can we achieve rendering an UI elements like paragraph,anchor,div tags etc.In the documentation it was mentioned that the in-browser utility modules may or may not render ui elements. Link for the documentation is https://single-spa.js.org/docs/module-types .
Any inputs on how to achieve this is appreciated.

Thanks in advance!!

VSCode does not auto-import from “react” in Next.js projects

* This is not a duplicate of this question; the accepted answer there is made for TypeScript and doesn’t seem to work for JavaScript.

I am working on a Next.js project in Visual Studio Code, and when trying to auto-import anything from "react", the only auto-import suggestions come from "react.production.min" and "react.development".

I can manually import from "react", but even when I already have an import { ... } from "react" statement in the file, it still doesn’t show up in the auto-import suggestions, and manually importing every hook I use can get quite tedious.

VSCode auto-import problem

Is there a way to fix this?

Running synchronous code within asynchronous code using AsyncHTMLSession object

I’m having issues running part of my code synchronously when using AsyncHTMLSession.

Need the following:

  1. logging with AsyncHTMLSession session (synchronously)
  2. retrieve responses to numerous links using a function (asynchronously)
  3. rendering responses to all html’s since site is dynamic (asynchronously)
  4. parsing all data (could be synchronously)

here’s the code:

def get_session_tasks(session):

tasks = []

for url in urls:
tasks.append(session.get(url))
return tasks

def get_render_tasks(responses):

tasks = []

for response in responses:
    tasks.append(response.html.arender(sleep=1))
return tasks

async def main():

with AsyncHTMLSession() as session:
    
    
    session_tasks = get_session_tasks(session)
    responses = await asyncio.gather(*session_tasks)
    render_tasks = get_render_tasks(responses)
    rendered_responses = await asyncio.gather(*render_tasks)

    return rendered_responses

rendered_responses = asyncio.run(main())
parse(rendered_responses) # parse is a synchronous function

Javascript editable text with syntax highlighting Prismjs

I’m looking to make a file editor with real time syntax highlighting and with my solution I need to call Prism.highlightElement at each keystroke as a synchronous function.
Currently, if my file has more than 100 lines, I have a time of plus 50 to 100 miliseconds for the function.

Do you know of any other technology that does this but is more suitable for real-time colouring?

Control java window open and close

I have a modal window that allows me to create new instance but I’m getting some strnge behaviour:

  • If I get error because the site already exists the window closes
  • If I manage to insert new site the window stays open

I need to reverse the behaviour.

const addBtn = document.getElementById('add-btn')
const modalBody = document.getElementById('model-body')
const siteForm = document.getElementById('site-form')
const alertBox = document.getElementById('alert-box')

const siteName = document.getElementById('id_name')
const siteCity = document.getElementById('id_city')
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value

const handleAlerts = (type, msg) => {
    alertBox.innerHTML = `
        <div class="alert alert-${type}" role="alert">
            ${msg}
        </div>
    `
}

function confirmExit() {
    return "You have attempted to leave this page. Are you sure?"
}

addBtn.addEventListener('click', ()=>{
       
    siteForm.addEventListener('submit', e=>{
        if (siteName.value ===''){
            handleAlerts('danger', 'Name field cannot be left empty')
            siteName.focus();
            window.onbeforeunload = confirmExit;
        }else{ 
            e.preventDefault()
            const formData = new FormData()
            formData.append('csrfmiddlewaretoken', csrf)
            formData.append('name', siteName.value)
            formData.append('city', siteCity.value)

            $.ajax({
                type: 'POST',
                url: '/savesite/',
                data: formData,
                success: function(response){                
                    handleAlerts('success', 'Site added')
                    siteForm.reset()                          
                },
                error: function(error){
                    console.log(error)
                    handleAlerts('danger', 'Site already exists in that city')
                },
                processData: false,
                contentType: false,
            })
            window.close();
        }
    })    
})

Load array of images in Canvas

I want to load an array of images to canvas but don’t know how to achieve it. I would appreciate it if I could get some pointers on how I can achieve it. I am using class-based component on React.

My Code:

drawCanvas(img, prevProps) {

const node = this.canvasRef.current;
const context = node.getContext("2d");


context.drawImage(img, 0, 0);
}

// imgArray = [image1, image2, image3]

componentDidUpdate(prevProps) {

  const imageArray = Array.from(imgArray).map((image) => image)

  console.log(imageArray)
  
  var img = new Image();
  img.src = this.props.image;
  img.onload = () => this.drawCanvas(img, prevProps);
}