Can’t unsubscribe from JavaScript event

I’m trying to use this piece of JavaScript to listen for keystrokes in a Blazor application.
It works fine by declaring a static method (JsKeyDown) on the page I would like to receive and handle the input on and subscribing to it using await JsRuntime.InvokeVoidAsync("JsFunctions.AddKeyboardListenerEvent"); but I would also need to be able to unregister from the event.
Since I have no clue when it comes to JS I was hoping someone could help me modify this from a what I believe to be an anonymous function that is being used to subscribe to the event to one that can also be used to unsubscribe e.g. RemoveKeyboardListenerEvent.

window.JsFunctions = {
    AddKeyboardListenerEvent: function (_) {
        let serializeEvent = function (e) {
            if (e) {
                return {
                    key: e.key,
                    code: e.keyCode.toString(),
                    location: e.location,
                    repeat: e.repeat,
                    ctrlKey: e.ctrlKey,
                    shiftKey: e.shiftKey,
                    altKey: e.altKey,
                    metaKey: e.metaKey,
                    type: e.type
                };
            }
        };
        
        window.document.addEventListener('keydown', function (e) {
            DotNet.invokeMethodAsync('ClassName', 'JsKeyDown', serializeEvent(e))
        });
    }
};

How can i make the first option of select element run after the page renders in react for the first time?

I have a select element in react with some options and i want the first option or the “selected” option to execute the value on screen when page is rendered initially. React for some reason doesn’t do it. My code is below

<p>{selectState}</p>
          <Select
            id="mySelect"
            value={selectState}
            onChange={(e) => setSelectState(e.target.value)}
          >
            <Option value="red" selected>Red</Option>
            <Option value="black">Black</Option>
            <Option value="blue">Blue</Option>
            <Option value="yellow">Yellow</Option>
          </Select>
          <Select>

the first

element shows me selected values but i want to see red being printed when the page loads for the first time, please tell me how i can do it.This is what i see when page loadsThis is what i want to see

Converting Images to USDZ Format for Websites

I’m a beginner when it comes to HTML and websites, but I’ve recently been experimenting with Python to convert images into STL format successfully. However, I’m facing a challenge when it comes to integrating the STL file into a website. What I’m trying to achieve is similar to the functionality found on the website https://imagetostl.com/, but instead of generating STL files, I want to convert images into USDZ format.

I’d greatly appreciate any guidance or suggestions on how to tackle this problem. Here’s a brief overview of what I’ve accomplished so far:

I’ve managed to convert images to STL format using Python.

However, I’m unsure how to effectively embed the resulting STL file into a website.

My ultimate goal is to convert images into USDZ format, on a website.

If anyone has experience working with USDZ conversion or integrating 3D files into websites, I would love to hear your insights. Specifically, I’m interested in understanding:

The process of converting images to USDZ format.

How to effectively embed USDZ files into a website.

Any recommended libraries, tools, or tutorials that can simplify this process.

Thank you so much in advance for your help and support. I’m eager to learn and explore this exciting field further!

I’ve managed to convert images to STL format using Python.

However, I’m unsure how to effectively embed the resulting STL file into a website.

How to get coordinates in double click – MapBox React

I plan on implementing a feature of displaying nearby routes when a user double clicks a location, but I dont know how to get the coordinates

This is my current code:

import React, { useState } from 'react';
import Map from 'react-map-gl';
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client';

const client = new ApolloClient({
  uri: TOKEN,
  cache: new InMemoryCache(),
});

function handleClick(map, event) {
  var lngLat = event.lngLat;
  console.log(lngLat)
}

function App() {

  return (
    <><ApolloProvider client={client}>
    </ApolloProvider>
    
    <Map
    mapboxAccessToken=TOKEN
    initialViewState={{
      longitude: 121.04042520880047,
      latitude: 14.649743779882588,
      zoom: 14
      }}
    style={{ width: window.innerWidth, height: window.innerHeight }}
    mapStyle="mapbox://styles/mapbox/light-v11"
    onDblClick={handleClick}
    ></Map>
    </>
  );
}

export default App

It leads to this Error:

ERROR
Cannot read properties of undefined (reading ‘lngLat’)
TypeError: Cannot read properties of undefined (reading ‘lngLat’)
at handleClick (http://localhost:3000/main.3e317df54a291f15fa87.hot-update.js:35:22)
at Mapbox._onPointerEvent (http://localhost:3000/static/js/bundle.js:34680:9)
at Map.fire (http://localhost:3000/static/js/vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:1007:32)
at Mapbox._fireEvent (http://localhost:3000/static/js/bundle.js:35107:14)
at hr._firePreventable (http://localhost:3000/static/js/vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:26089:23)
at hr.dblclick (http://localhost:3000/static/js/vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:26068:21)
at Xr.handleEvent (http://localhost:3000/static/js/vendors-node_modules_mapbox-gl_dist_mapbox-gl_js.chunk.js:27078:93)

Laravel with Vite: Issue with infinite loading when adding `@vite(‘resources/css/app.css’)` to view

I am currently facing an issue when trying to load my Laravel application with Vite. Specifically, when I add the @vite('resources/css/app.css') directive to my view, the loading process seems to hang indefinitely. However, if I remove the @vite directive, the loading works without css.

I suspect that there might be a problem with tailwind or another factor that is causing this issue. Here are some additional details and steps I have taken:

Environment Details:

  • Operating System: WSL Ubuntu

  • PHP Version: 8.1.2

  • Laravel Framework Version: 10.15.0

  • Vite Version: 4.4.3

  • Vite configuration:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/sass/app.scss',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm-bundler.js',
        },
    },
});

  • Blade template:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>aaa</title>
  @vite('resources/css/app.css')
</head>

<body class="bg-white">
  @yield('content')
</body>

</html>
  • Error messages: theres no erro messages in chrome console, npm run dev and, php artisan serve

I have tried searching for solutions, but I couldn’t find any that addressed this specific issue. I would greatly appreciate any guidance or suggestions on how to resolve this problem.

Thank you in advance for your time and assistance!

I want to those div which have no data

I distributed my php report in 2 div section. Both div data came from one mysql table. I am trying to implement that if any of the those 2 div have no data to show, then div should be hide along with column headings.
Here is my php code

                    <div class = "One">
                  echo '<table class="styled-table">';
                        echo "<thead>";
                            echo "<tr>";                                  
                               
            echo "<th>Name</th>";
            echo "<th>Phone</th>";
            echo "<th>Age</th>";        
                               
                                echo "<th>Action</th>";
                            echo "</tr>";
                        echo "</thead>";
                        echo "<tbody>";
                        while($row = mysqli_fetch_array($result)){
                            echo "<tr>";                                       
                                echo "<td>" . $row['pname'] . "</td>";
            echo "<td>" . $row['phone1'] . "</td>";
            echo "<td>" . $row['age'] . "</td>";                
                             
                                echo "<td>";  </div>

             

                  <div class = "TWO">
              echo '<table class="styled-table">';
                    echo "<thead>";
                        echo "<tr>";                                  
                           
        echo "<th>address</th>";
        echo "<th>City</th>";
        echo "<th>Country</th>";        
                           
                            echo "<th>Action</th>";
                        echo "</tr>";
                    echo "</thead>";
                    echo "<tbody>";
                    while($row = mysqli_fetch_array($result)){
                        echo "<tr>";                                       
                            echo "<td>" . $row['address'] . "</td>";
        echo "<td>" . $row['city'] . "</td>";
        echo "<td>" . $row['country'] . "</td>";                
                         
                            echo "<td>";  </div>

Rendering nextjs component based on env value

I want to show a maintenance message to my users based on an env value but it just isnt working.

I have a value in my .env.local which is;

NEXT_PUBLIC_SHOW_MAINTENANCE=true

and my page looks like so;

const Index = () => {
    const showMaintenance = process.env.NEXT_PUBLIC_SHOW_MAINTENANCE

    return (
        <div>
            {showMaintenance ? (
                <div>Under Maintenance</div>
            ) : (
                <div>We are live</div>
            )}
        <div/>
    )
}

export default Index

But its just not working at all, if the value is true or false it just shows Under Maintenance.

Any help would be greatly appreciated.

Recursive function to filter out array of objects based on ID regardless of parent or children elements [duplicate]

I need to filter below array of objects based on ID regardless of parent or child, if _id is found in the parent then remove that element and return rest, and if id is found in child than remove that child element and return rest.

const arrayToBeFiltered = [
  {
    _id: "1",
    assets: [
      {
        _id: "2",
      },
      {
        _id: "3",
      },
    ],
  },
  {
    _id: "4",
    assets: [
      {
        _id: "5",
      },
    ],
  },
];

So, if I pass 3 then it should return:

[
  {
    _id: "1",
    assets: [
      {
        _id: "2",
      },
    ],
  },
  {
    _id: "4",
    assets: [
      {
        _id: "5",
      },
    ],
  },
];

And if I pass 4 then it should return:

[
  {
    _id: "1",
    assets: [
      {
        _id: "2",
      },
      {
        _id: "3",
      },
    ],
  },
];

Why Tailwind css not work in vite+react project

I created a React application using Vite and used the documentation provided here to install Tailwind: Tailwind CSS Installation Guide.

however still not working tailwind css in my react application.

tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
    content: [
        "./index.html",
        "./src/**/*.{js,ts,jsx,tsx}",
    ],
    theme: {
        extend: {},
    },
    plugins: [],

}

postcss.config.js

export default {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
}

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

package.json

  "devDependencies": {
    "@types/react": "^18.2.14",
    "@types/react-dom": "^18.2.6",
    "@vitejs/plugin-react": "^4.0.1",
    "autoprefixer": "^10.4.14",
    "eslint": "^8.44.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.1",
    "postcss": "^8.4.26",
    "tailwindcss": "^3.3.3",
    "vite": "^4.4.0"
  }

index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

but still not show this designs

App.jsx

function App() {

  return (
    <div>
      <h1 className='head-text'>React App</h1>
      <p className="text-yellow-500">Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, quasi.</p>
    </div>
  )
}

export default App

can’t use setAttribute() for tailwindcss

I’m completely new to tailwindcss. I’m currently trying to dynamically create div and set its tailwind styles using javascript, for example, I’ve a code like below:

var div = document.createElement("div");
div.setAttribute("style", "bg-slate-800");

the bg-slate-800 does not show up…..

My questions is: is this not supported by tailwindcss ? if so, how could I make it work ?

Thanks!

I tried:

var div = document.createElement("div");
div.setAttribute("style", "bg-slate-800");

the bg-slate-800 doesn’t apply. However, if I try like this:

var div = document.createElement("div");
div.setAttribute("style", "background-color:#000000");

it works perfectly fine.

Can you help me to find the answer how I can disable clicks after winning status

I have tried so many concepts but finally not able to conclude the answer. I have made a tic-tac-toe game, which is fully functioning but I have problem that when I my winning status is displayed on windisplay column , after that also I am able to take input from user.

Please help me to resolve the problem. I want to disable my boxes click when a winner is found.

    const PlayerFactory = (name, mark, turn) => {
        return { name, mark, turn }
    };

    var p1arr = [];
    var p2arr = [];
    const player1 = PlayerFactory("Player 1", "X", true);
    const player2 = PlayerFactory("Player 2", "O", false);

    const windisplay = document.querySelector('.win-display');

    var boxes = document.getElementsByClassName("box");

    let gameover = false;

    if (gameover) {
        return;
    }
    
    for (var i = 0; i < boxes.length; i++) {
        boxes[i].addEventListener("click", function () {
            boxClicked(this);
        });

    }

    function boxClicked(box) {
        if (box.innerHTML === "") {
            if (player1.turn === true) {
                box.textContent = player1.mark;
                // alert("Kaam 1 ho gya");
                p1arr[box.id] = player1.mark;
                console.log(p1arr);
                player1.turn = false;
                player2.turn = true;
                checkwinner();
            }
            else if (player2.turn === true) {
                box.textContent = player2.mark;
                // alert("Kaam 2 ho gya");
                p2arr[box.id] = player2.mark;
                console.log(p2arr);
                player1.turn = true;
                player2.turn = false;
                checkwinner();
            }
        } else {
            console.log("This box is already occupied!");
        }
    }

    const winCombos = [
        [0, 1, 2],
        [0, 3, 6],
        [3, 4, 5],
        [6, 7, 8],
        [1, 4, 7],
        [2, 4, 6],
        [2, 5, 8],
        [0, 4, 8]
    ];

    function checkwinner() {
        // Check if any winCombos match the numbers in array1
        var isWinner1 = checkWinCombos(p1arr);
        if (isWinner1) {
            console.log("Winner is X! ");
            windisplay.textContent = "Winner is X! ";
            gameover = true;
        }

        // Check if any winCombos match the numbers in array2
        var isWinner2 = checkWinCombos(p2arr);
        if (isWinner2) {
            console.log("Winner is O!");
            windisplay.textContent = "Winner is O! ";
            gameover = true;
        }


        // Function to check if any winCombos match the given array
        function checkWinCombos(array) {
            for (var i = 0; i < winCombos.length; i++) {
                var combo = winCombos[i];
                var isMatch = true;
                for (var j = 0; j < combo.length; j++) {
                    if (!array[combo[j]]) {
                        isMatch = false;
                        break;
                    }
                }
                if (isMatch) {
                    return true;
                }
            }
            return false;
        }

        // Function to count occurrences of 'X' and 'O' in an array
        function countOccurrences(array, symbol) {
            let count = 0;
            for (let i = 0; i < array.length; i++) {
                if (array[i] === symbol) {
                    count++;
                }
            }
            return count;
        }

        // Count the occurrences of 'X' and 'O' in both arrays
        const oCount = countOccurrences(p1arr, 'O') + countOccurrences(p2arr, 'O');
        const xCount = countOccurrences(p1arr, 'X') + countOccurrences(p2arr, 'X');

        // Check if all 9 boxes are occupied
        if (xCount + oCount === 9) {
            console.log('Tie!');
            windisplay.textContent = "Tie!";
        }

    }

    let resetbutton = document.querySelector('.reset')
    resetbutton.addEventListener('click', function () {
        // alert("Kaam ho gya!");
        resetgame();
    });

    function resetgame() {
        p1arr = [];
        p2arr = [];
        for (var i = 0; i < boxes.length; i++) {
            boxes[i].innerHTML = "";
        }
        windisplay.textContent = "";
    }

})();

Why is my client side script messing with my server side rendering?

I am building a flask app where a users input is collected via a form (#questions) and submitted via post. Once received by the server the template is to be rendered again with a simple message ‘hi’ displayed in a read only text area at the bottom of the page.

Everything works well until I introduce Javascript in the script tag on the index.html page. The purpose of this script is to show a spinner while the client side waits for the server request to be completed. It serves this purpose, and there are no errors in the console, however it seems to be preventing the page from being rendered again with the response in the textarea.

I am new to JavaScript so I’m sure I am missing some logic. I’m just not sure what it is. Can anyone help me out?

Client side code with script (I have removed the form for brevity):

<!DOCTYPE html>
<head>
  <title>Security Policy Generator</title>
  <link rel="stylesheet" href="{{ url_for('static',filename='output.css') }}" />
 <script>
    document.addEventListener('DOMContentLoaded', function(){
    document.querySelector('#questions').addEventListener('submit', function(event) {
    event.preventDefault();

    document.querySelector('#spinner').style.visibility = 'visible';
    

    var httpRequest = new XMLHttpRequest();

    var formData = new FormData(document.getElementById("questions"));

    httpRequest.open('POST', '/', true);
    httpRequest.onreadystatechange = function(){
      if (httpRequest.redyState === 4 && httpRequest.status === 200) {
        document.querySelector('#spinner').style.visibility = 'invisible';
      }
    };
    httpRequest.send(formData);
    console.log('success');

    return false;
    });
  });
  </script>
</head>
<body class="bg-black">
  <div class='bg-center bg-white py-8 px-6 shadow rounded-lg sm:px-10 mx-auto max-w-screen-xl text-center bg-no-repeat bg-blend-multiply' >
    <form id="questions" class='mb-0 space-y-6' action="/" method="POST">
      <input class="bg-blue-500 hover:bg-indigo-500 text-white font-bold py-2 px-4 border border-indigo-500 rounded" type="submit" value="Submit" />
      <div id="spinner" class="invisible" role="status">
        <svg aria-hidden="true" class="inline w-8 h-8 mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-red-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
            <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
        </svg>
        <span class="sr-only">Loading...</span>
    </div>
    </form>
  </div>
  {% if result %}
  <div class='bg-white py-8 px-6 shadow rounded-lg sm:px-10 mx-auto max-w-screen-xl text-left'>
    <textarea class='result w-full border border-gray-300 rounded-lg
        shadow-sm focus:outline-none focus:border-indigo-500 focus:ring
        focus:ring-indigo-500 block text-sm font-medium text-gray-700' readOnly='True'>{{ result }}</textarea> 
  </div>
  {% endif %}
</body>`

Server side code:

from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)



@app.route("/", methods=("GET", "POST"))
def index():
    if request.method == 'POST':
        policy_type = request.form['option']
        industry = request.form['industry']
        business_name = request.form["business-name"]
        framework = request.form['framework']
        result = 'hi'
        return render_template('index.html', result=result)
    
    result = request.args.get('result')
    return render_template('index.html',  result=result)

CSR Routing error when using loader in React

I was playing with ‘fetch’ function with ‘loader’ in ‘react-router’ and encountered an error, and I have been trying to resolve it for three days, but I still haven’t been successful.

Symtoms is like this.

  1. When I call local json file through fetch function within ‘loader’ in Homepage, it worked successfully.
    But, I found the error only if I move from deep level page to Homepage ( ‘/events/event/1’ -> ‘/’) which trigger loader. But error disappear and I tried refresh then it was rendered well normally.

  2. there is no error when routing from same level or lower element (‘/events’ <->’/’)

and my directory is like this:

enter image description here

//App.js
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import EditEventPage from "./routers/EditEventPage";
import NewEventPage from "./routers/NewEventPage";
import { EventsPage, Loader as eventsLoader } from "./routers/EventsPage";
import EventDetailPage from "./routers/EventDetailPage";
import { HomePage, Test } from "./routers/Homepage";
import Root from "./routers/Root";
const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    children: [
      { index: true, element: <HomePage />, loader: Test },
      { path: "/events", element: <EventsPage />, loader: Test },
      { path: "events/:id", element: <EventDetailPage /> },
      { path: "events/new", element: <NewEventPage /> },
      { path: "events/:id/edit", element: <EditEventPage /> },
    ],
  },
]);

function App() {
  return (
    <>
      <RouterProvider router={router} />
    </>
  );
}

export default App;
//Homepage.jsx
import { useLoaderData } from "react-router-dom";
export function HomePage() {
  const postings = useLoaderData();
  console.log(postings);
  return;
}
export async function Test() {
  const data = await fetch("./postings.json");
  const parsed = await data.json();
  console.log("fetch completed");
  return parsed;
}
//eventsPage.jsx
import { useEffect, useState } from "react";
import { useLoaderData } from "react-router-dom";
import EventsList from "../components/EventsList";

export function EventsPage() {
  //   const [isLoading, setIsLoading] = useState(false);
  const [fetchedEvents, setFetchedEvents] = useState();
  //   const [error, setError] = useState("");
  const data = useLoaderData();
  useEffect(() => {
    setFetchedEvents(data.events);
  }, []);
  return (
    <>
      <div style={{ textAlign: "center" }}>
        {/* {isLoading && <p>Loading...</p>} */}
        {/* {error && <p>{error}</p>} */}
      </div>
      {fetchedEvents && <EventsList events={fetchedEvents} />}
    </>
  );
}

I found that several hints to resolve this problem

  1. This error happens only if I fetch local directory files. If I change only url in fetch function which makes all the code works, then the error disappears.

  2. I’ve realized that this is CSR (Client Side Rendering) error. So When I refresh, it request to server and there was no problem. but the bug is only in the CSR

I’m very new to this programming world so please help me