Send Search Results to New Route – React, JS

I am trying to send my resultsArray data to another route “/search-results”. I have been using useNavigate() but by the time the page is showcased the results are not there. It says “no results found” I think it is a time issue, the page is loading faster than the results can populate. Please review my code and help! Thank you!

SearchBar Component:

    import { useState } from "react";
    import React from "react";
    import SearchResults from "./SearchResults";
    import { useNavigate } from "react-router-dom";
    import "../../CSS/Search.css";
    import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
    import { faSearch } from "@fortawesome/free-solid-svg-icons";
    
    
    //mock data 
    import mockData from "./mockData";
    
    export default function SearchBar() {
        // const [results, setResults] = useState([]);
        const [shoppingResults, setShoppingResults] = useState([]);
        const [loading, setLoading] = useState(false);
        const [searchInput, setSearchInput] = useState("");
    
        const navigate = useNavigate(); 
    
        const handleSearch = async (e) => {
        //remove this for MVP version
          setLoading(true);
    
            e.preventDefault();
            setSearchInput(e.target.value);
            // performSearch(searchInput);
    
            //remove this for MVP version
            const filteredResults = mockData.filter(item => item.title.toLowerCase().includes(searchInput.toLowerCase())
            );
    
            
            setTimeout(() => {
              setShoppingResults(filteredResults);
              setLoading(false);
            }, 1000);
    
        };
        return (
            <div className="search-bar-container">
              <div className="search-bar">
                <input className="search-bar-bar"
                    type="text"
                    placeholder="Search"
                    value={searchInput}
                    onChange={(e) => setSearchInput(e.target.value)}
                    style={{ textAlign: "center" }}
                />
                <button className="search-button" onClick={handleSearch}><FontAwesomeIcon icon={faSearch} size="lg" style={{color: "#231a1f",fontSize: "24px", fontWeight: "bold"}} /></button>
              </div>
              <div className="searchResults">
                    {loading ? (
                    <div>Loading...</div>
                     ) : (
                        <SearchResults resultsArray={shoppingResults} />
                     )}
              </div>
              <div className="message">
                  <ul>
                    <li>What's on your list?</li>
                    <li>Start your search above</li>
                  </ul>
              </div>
            </div>
           
        );
    };

SearchResults Component:

    import "../../CSS/SearchResults.css"
    // import { useParams } from "react-router-dom";
    
    export default function SearchResults({ resultsArray }) {
        return (
            <div className="result-page">
                <div className="results-container">
                {resultsArray ? (
                     resultsArray.map((result, index) => (
                        <div key={index} className="item-containter">
                            <div key={index} className="item-image"><img src={result.thumbnail} alt="Product Thumbnail" /></div>
                            <div key={index} className="item-facts">product rating: {result.rating}</div>
                            <div key={index} className="store-container">
                                <div key={index} className="store-logo"></div>
                                <div className="store-options">
                                {result.title} {result.price}</div>
                            </div>
                        </div>
                    ))
                ):(
                    <div>No results found</div>
                )}
                </div>
            </div>
    
        )
    }

Results Page:

import SearchResults from "../Components/Searches/SearchResults";

export default function Results() {
    return (
        <div className="search-results">
            <SearchResults />
        </div>
    );
};

app.js:

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import React from "react";

// PAGES
import Home from "./Pages/Home";
import Search from "./Pages/Search";
import Results from "./Pages/Results"


function App() {
  return (

    <div className="App">

      <Router>
         {/* <NavBar /> */}
        <NavBar />
        <main>
          <Routes>
            <Route path="/" element={<Landing />} />
            <Route path="/about" element={<About/>} />
            <Route path="/search" element={<Search />} />
            <Route path="/search-results" element={<Results />} />
            <Route path="/register" element={<Register />} />
            <Route path="/login" element={<LogIn />} />
          </Routes>
        </main>
      </Router>
    </div>
  );
}

export default App;

Selecting the Default profile on Microsoft Edge with Selenium (session not created: DevToolsActivePort file doesn’t exist)

I have the following code:

import { Builder } from 'selenium-webdriver'
import edge from 'selenium-webdriver/edge'

export async function getBrowserDriver() {
  const browser = 'MicrosoftEdge'

  const edgeOptions = new edge.Options()
  edgeOptions.addArguments(`--user-data-dir=C:\Users\bruno\AppData\Local\Microsoft\Edge\User Data\`)
  edgeOptions.addArguments('--profile-directory=Default')
  edgeOptions.addArguments('--disable-dev-shm-usage')
  edgeOptions.addArguments('--no-sandbox')
  // edgeOptions.addArguments('--disable-dev-tools')
  // edgeOptions.addArguments('--remote-debugging-port=9222')


  return new Builder()
    .forBrowser(browser)
    .setEdgeOptions(edgeOptions)
    .build()
}

This works if I swap everything to use Chrome, everything just works. However, when I try the exact same using Edge I run into this error:

SessionNotCreatedError: session not created: Microsoft Edge failed to start: exited normally.
  (session not created: DevToolsActivePort file doesn't exist)
  (The process started from msedge location C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe is no longer running, so msedgedriver is assuming that msedge has crashed.)
    at Object.throwDecodedError (C:BrunoLMProjectsxappnode_modulesselenium-webdriverliberror.js:524:15)
    at parseHttpResponse (C:BrunoLMProjectsxappnode_modulesselenium-webdriverlibhttp.js:601:13)
    at Executor.execute (C:BrunoLMProjectsxappnode_modulesselenium-webdriverlibhttp.js:529:28)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I have seen suggestions to use --disable-dev-shm-usage and also --no-sandbox, AI even suggested --disable-dev-tools. Nothing works. I’ve tried a few combinations and I either get this error or an error saying that it couldn’t even reach chrome.

AI also suggested I installed npm install -g webdriver-manager and ran webdriver-manager update. I’ve tried that too, but it made no difference.

I downloaded the msedgedriver.exe and I think I was able to hook it up with selenium with

    const driver = new Builder()
    .forBrowser('MicrosoftEdge')
    .usingServer('http://localhost:9515').setEdgeOptions(edgeOptions).build()

    return driver

I did see some logs:

Starting Microsoft Edge WebDriver 119.0.2151.44 (x) on port 9515
To submit feedback, report a bug, or suggest new features, please visit https://github.com/MicrosoftEdge/EdgeWebDriver

Only local connections are allowed.
Please see https://aka.ms/WebDriverSecurity for suggestions on keeping Microsoft Edge WebDriver safe.

Microsoft Edge WebDriver was started successfully.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.
Opening in existing browser session.

But it doesn’t matter what I try it ends up in:

DevToolsActivePort file doesn't exist

It opens a browser window, but it crashes, and I have the window open but can’t access it at all.

Am I doing something wrong or is it an issue with the driver or Edge? Is there any way to fix it? Maybe downgrade something?

How do i modify this cors proxy to pass all the body parameters in my request

I am currently making a chrome extension that successfully gets some information from the content script and passes it to the background script (“jobInfo”). I want to send the information to mongoDB atlas database that has a data API running through the use of an API key. But, I was receiving CORS preflight errors because of which I decided to connect to data API through a proxy. I found a proxy on https://medium.com/nodejsmadeeasy/a-simple-cors-proxy-for-javascript-applications-9b36a8d39c51 which seemed to fit what I wanted to do. I modified the url part within the request so that it would send to the correct endpoint and it is reflected in the logs on mongoDB(no error but nothing gets added to db). But, there is something wrong with how the body of my request is being passed since I get the response : “Failed to insert document: Invalid or unspecified ‘dataSource’, ‘database’, or ‘collection’ field'” . I would appreciate it if someone could guide me on how I should modify this proxy so that I can successfully pass my request with all body parameters.

Note: I’m planning on sending jobInfo in the “document” field but I’m just sending something else to test.

Background.js:

console.log("bg script running")

const url = "http://127.0.0.1:3000/"
const target_url = "https://us-east-2.aws.data.mongodb-api.com/app/$my_id/endpoint/data/v1/action/insertOne";

chrome.action.onClicked.addListener((tab) => {
  
  (async () => {
    const jobInfo = await chrome.tabs.sendMessage(tab.id, {status: "pressed"});
    console.log("message passed")
    console.log(jobInfo)

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "apiKey" : "my_key",
        "Content-Type" : "application/ejson",
        "Accept" : "application/json",
        "Target-URL" : target_url
      },
      body: JSON.stringify({
        dataSource: "my_cluster",
        database: "my_db",
        collection:"my_col",
        document: {
          "status": "open",
          "text"  : "Do the dishes"
        }
      })
    });

    console.log(response)

  })();


});

cors-proxy.js:

var express = require('express'),
    request = require('request'),
    bodyParser = require('body-parser'),
    app = express();

var myLimit = typeof(process.argv[2]) != 'undefined' ? process.argv[2] : '100kb';
console.log('Using limit: ', myLimit);

app.use(bodyParser.json({limit: myLimit}));

app.all('*', function (req, res, next) {

    // Set CORS headers: allow all origins, methods, and headers: you may want to lock this down in a production environment
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
    res.header("Access-Control-Allow-Headers", req.header('access-control-request-headers'));

    if (req.method === 'OPTIONS') {
        // CORS Preflight
        res.send();
    } else {
        var targetURL = req.header('Target-URL'); // Target-URL ie. https://example.com or http://example.com
        if (!targetURL) {
            res.send(500, { error: 'There is no Target-Endpoint header in the request' });
            return;
        }
        request({ url: (targetURL + req.url).slice(0,-1), method: req.method, json: req.body, headers: {'Authorization': req.header('Authorization'),'apiKey': req.header('apiKey'),'Content-Type': req.header('Content-Type'),'Accept': req.header('Accept')} },
            function (error, response, body) {
                if (error) {
                    console.error('error: ' + response.statusCode)
                }
//                console.log(body);
            }).pipe(res);
    }
});

app.set('port', process.env.PORT || 3000);

app.listen(app.get('port'), function () {
    console.log('Proxy server listening on port ' + app.get('port'));
});

enter image description here

enter image description here

Preventing Low Values from Clustering at Center in Chart.js Radar Chart

import React from "react";
import { Radar } from "react-chartjs-2";
import {
  Chart,
  RadialLinearScale,
  CategoryScale,
  PointElement,
  LineElement,
  RadarController
} from "chart.js";

Chart.register(
  RadialLinearScale,
  CategoryScale,
  PointElement,
  LineElement,
  RadarController
);

const RadarChartSimple = () => {
  const data = {
    labels: ["Spanish", "English", "French", "Dutch", "German"],
    datasets: [
      {
        label: "Language Proficiency",
        data: [100, 98, 95, 60, 40],
        backgroundColor: "rgba(108, 46, 156, 0.4)", // Opacidad del relleno
        borderColor: "#6c2e9c", // Color del borde
        borderWidth: 1,
        pointBackgroundColor: "#6c2e9c",
        pointRadius: 0 // Esto hará que los puntos de datos no se dibujen
      }
    ]
  };

  const options = {
    scale: {
      ticks: {
        beginAtZero: true,
        max: 100,
        stepSize: 20,
        display: false, // Esto debería ocultar los números del eje radial
        showLabelBackdrop: false // Esto debería ocultar el fondo de las etiquetas
      },
      gridLines: {
        color: "#0d284f"
      },
      angleLines: {
        color: "#0d284f"
      },
      pointLabels: {
        fontColor: "#eadbc8",
        fontSize: 16, // Ajusta este valor según lo que necesites
        fontStyle: "bold" // Esto hará que el texto sea negrita
      },
      backgroundColor: "#eadbc8"
    },
    legend: {
      display: false
    },
    maintainAspectRatio: false
  };

  return (
    <div style={{ height: "300px", width: "100%" }}>
      <Radar data={data} options={options} />
    </div>
  );
};

export default RadarChartSimple;

The problem I’m facing is with a radar chart created using react-chartjs-2 and Chart.js. I have a set of values representing language proficiency levels that are plotted on the radar chart. Most values are represented correctly except for the lower values, specifically a score of 40 for German, which is incorrectly clustering at the center of the radar chart.

Despite setting the beginAtZero option to true in the scale options, which I expected would ensure that the plotting starts from the edge of the chart, this particular value is not being placed accurately according to its scale. It’s visually misleading as it gives the impression that the proficiency level for German is lower than it actually is.

The issue persists even after several attempts to fix it, such as adjusting the suggestedMin and max properties, and ensuring there is no conflicting CSS or global styles. I’m looking for a solution that would allow all the data points, no matter how small, to be placed proportionately on the radar chart, giving an accurate visual representation of the data.

I’ve tried adjusting the ticks configuration within the options for the chart, specifically setting beginAtZero to true, with the expectation that it would cause all the data points to originate from the outermost edge of the chart, not the center. Additionally, I set the pointRadius to 0 to remove the data point dots, as they are not needed for my visualization.

I also attempted to manipulate the max, stepSize, and display properties within the ticks configuration to see if they would correct the placement of the 40 value for German. My expectation was that these changes would ensure each data point is plotted accurately in proportion to its value, with no points unnaturally clustered at the center when they should be closer to the edge.

However, contrary to these expectations, the 40 value for German remains improperly positioned at the center of the chart, which visually misrepresents the data. This issue persists and seems unaffected by the changes in the chart configuration or the removal of potentially conflicting global styles and CSS.

Limit the Primefaces datePicker minutes and seconds from Javascript

I am using a datePicker Primefaces element in order to allow the user to select a value for the hours, minutes and seconds. Currently, the hour has values between 0 and 24, the minutes are between 0 and 60 and same for the seconds.

I want to limit this possibility of choice to some static values, obtained from getting the length of a video posted on the page.I have in JS the value for the hours, for the minutes and for the seconds.

So, for example, if the video has 1 minute and 30 seconds, I want the hours part not to allow the user to press the arrow up or down, the minutes to be maximum 30 and the minutes 1. I tried the below approach with JS, but I get the error: “timePicker.setMaxTime is not a function”. In Java, I can set on the Primefaces datePicker minDate and maxDate, but I do not know the length of the video there, I can only find it from JS.

What can I do?

The UI datePicker element:

                                <p:datePicker id="timeDatePicker"
                                              widgetVar="widgetVarOfDatePicker"
                                              value="#{traineeDashboard.newIncidentTimestamp}"
                                              appendTo="@this">
                                    <f:converter converterId="timeConverter"/>
                                </p:datePicker> 

The JS code:

    var timePicker = PF('widgetVarOfDatePicker'); // Replace with your actual widgetVar
    var hoursDropdown = $('div.ui-hour-picker span:eq(1)');
    var minutesDropdown = $('div.ui-minute-picker span:eq(1)');
    var secondsDropdown = $('div.ui-second-picker span:eq(1)');

    hoursDropdown.text(hours);
    minutesDropdown.text(minutes);
    secondsDropdown.text(seconds);

    if (hours == 0) {
        timePicker.setMaxTime(minutes, seconds);
    } else {
        timePicker.setMinTime(hours, minutes);
    }

    hoursDropdown.trigger('change');
    minutesDropdown.trigger('change');
    secondsDropdown.trigger('change');
} 

CKEditor5 reinitializing the toolbar options programmatically without reinitializing the whole editor

Using CKEditor5 I’ve initialized a toolbar with a certain number of options.
However when a checkbox is selected, I would like to reinitialize just the toolbar with less or more toolbar options, without destroying the CKEditor and reinitializing the whole editor again.

Is there a way this can be done programmatically in javascript/jquery? I see examples for ckeditor4 but have not seen anything for ckeditor5.

Thank you in advance.

Below is how I have my CKEditor5 initialized:


<html>
<div class="mb-3 row">
            <label class="col-lg-2 col-form-label">Bulletin Text</label>
            <div class="col-lg-10">
                @Html.TextAreaFor(m => m.BulletinText, new { @id = "BulletinText", @style = "display:none;" })
            </div>
        </div>
</html>

<script>
let theEditor;

ClassicEditor
        .create(document.querySelector('#BulletinText'), {
            ckfinder: {
                uploadUrl: '/ckfinder/connector?command=QuickUpload&type=Files&responseType=json'
            },
            removePlugins: ['MediaEmbedToolbar']
            },
            alignment: {
                options: ['left', 'right', 'center', 'justify']
            },
            toolbar: {
                items: [
                    'heading', '|',
                    'bold', 'italic', 'strikethrough', 'underline', 'subscript', 'superscript', '|',
                    'fontfamily', 'fontsize', 'fontcolor', 'fontbackgroundcolor', 'highlight', '|',
                    'link', '|',
                    'bulletedlist', 'numberedlist', '-', //todolist
                    'outdent', 'indent', 'alignment', '|',
                    'horizontalline', 'blockquote', 'inserttable', '|',
                    //'-', //page break
                    'ckfinder', 'imageupload', '|', //'mediaembed',
                    'sourceediting', '|',
                    'undo', 'redo', "specialCharacters"
                ]
            }
        })
        .then(editor => {
theEditor = editor;
            console.log(editor);
        })
        .catch(error => {
            console.error(error);
        });
</script>

How to syncronize the elimination of two components

Lets say I have two componentes that display a common component when I make a delete request to the api inside one of the componentes the other component does not get deleted until I refresh the browser how can I fix that such that the common component gets eliminated at the same time

here are the components:

import React, { useEffect, useState } from "react";
import { getTasks } from "../api/task.api";
import { TaskCard } from "./TaskCard";

export function TaskLists() {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    async function loadTasks() {
      const res = await getTasks();
      console.log(res.data);
      setTasks(res.data);
    }
    loadTasks();
  }, []);

  const removeTask = (id) => {
    setTasks(tasks.filter((task) => task.id !== id));
  };

  return (
    <div>
      {tasks.map((task) => (
        <TaskCard key={task.id} task={task} onDelete={removeTask} />
      ))}
    </div>
  );
}

and

import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import { getTasks } from "../api/task.api";
import { TaskCard } from "./TaskCard";

export function Daycard({ hashv }) {
  let b = 0;
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    async function loadTasks() {
      const res = await getTasks();
      console.log(res.data);
      setTasks(res.data);
    }
    loadTasks();
  }, []);

  const removeTask = (id) => {
    setTasks(tasks.filter((task) => task.id !== id));
  };

  const [hash, setHash] = useState(hashv);
  const navigate = useNavigate();
  const handleClick = () => {
    if (b === 0) {
      navigate(`/tasks-create?hash=${hash}`);
      console.log(`the hash is ${hash}`);
    }
  };

  return (
    <div
      onClick={handleClick}
      className="col pb-5 bg-light border border-dark flex-grow-1"
      style={{ height: "auto" }}
    >
      {tasks.map((task) => {
        if (task.hash == hash) {
          b = 1;
          return <TaskCard key={task.id} task={task} onDelete={removeTask} />;
        }
      })}
    </div>
  );
}

Behavior pressing delete inside the card:

enter image description here

enter image description here

Hijacking addEventListener results in too much recursion when adding a react-invokeguardedcallback listener to HTMLUnknownElement

I have a use case where I’d like to monitor event listeners being added. I found a method to do this that worked for me here: https://stackoverflow.com/a/6434924

This code seems to work in many situations, but, it would seem it will throw a InternalError: too much recursion exception when used on a page containing a react app.

Simplest reproducer looks like this:

Node.prototype.realAddEventListener = Node.prototype.addEventListener;

Node.prototype.addEventListener = function(a,b,c){
    this.realAddEventListener(a,b,c);
}

Printing this , a, and b just before the error happens yields:

this = [object HTMLUnknownElement] 

a = react-invokeguardedcallback 

b = function callCallback() {
        // We immediately remove the callback from event listeners so that
        // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
        // nested call would trigger the fake event handlers of any call higher
        // in the stack.
        fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
        // window.event assignment in both IE <= 10 as they throw an error
        // "Member not found" in strict mode, and in Firefox which does not
        // support window.event.

        if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
          window.event = windowEvent;
        }

        func.apply(context, funcArgs);
        didError = false;
      }

What is it about adding a listener to an HTMLUnknownElement on the react-invokeguardedcallback with the function handler above that causes my hijacked addEventListener to recurse?

How to fix TypeError: null is not an object (evaluating ‘j.current.useRef’) when my app is deployed on Heroku?

This is my last resort, I’ve tried fixing this for the past 3 days but I don’t even know how to begin tackling the problem and all my research seems to point toward people who are actually using useRef in their application and I’m not using it at all, as far as I know.

I’m working on a social media website on the PERN stack that I’m trying to deploy on heroku. When serving the application on my machine either through serve -s build in the client folder or simply going to “/” from my backend index.js file, the application works exactly as expected. However, when it’s deployed on heroku, the page won’t render at all and gives me two errors, both related to useRef: My console whenever I try going to the page on heroku.

My question is, what am I supposed to change to make this work? I don’t use useRef at all in my application, but I do use useEffect a lot, so I’m not sure if the issue is my code or a missing dependency. Either way, it seems to not be an issue when I’m running it on my machine, so I’m not sure where to look for errors caused by react-dom.production. I would appreciate any step in the right direction for fixing this error, as it seems like nobody’s had this issue on the site.

I’ve tried removing the StrictMode wrapper from my index.js file in the client folder to see if that would change anything. I figure the browser can’t access whatever value it needs for useRef but I don’t understand why it seems to work on my machine and won’t work from heroku. I do have react-router-dom in both the package.json files for my client and my backend, could this be the issue? If I dont add it to my backend node-modules the app will fail to deploy since it won’t resolve it.

Here’s a link to my code, I wish I could add code snippets but since I don’t even use useRef in my app I have no idea what is actually causing this issue. If you see anything that’s wrong please feel free to criticize, I’m open to any suggestions.

window.scrollY value is controlled by wrong ScrollBar

I’m trying to integrate a scroll bar to a dynamic table after the height is 275px. The scroll bar is functional after the table reaches 275px, however, when I use the table scroll bar, I do not see any change to the window.scrollY value. Instead, The scroll bar for the entire page is changing the value of window.scrollY, which is not what I need.

Here is a snippet of my table container:

// Define Table Container and add it to the parent container
var tableContainer = $('<div>').css({
  'max-width': '55px',
  'max-height': '275px',
  'overflow-y': 'scroll',
  'border': '1px solid black', // Add a border for visualization
});


let scrollPosition = 0;

function handleScroll() {
  scrollPosition = window.scrollY;
  console.log("PosY = ", scrollPosition);
}

let my_array = [
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6],
  [1, 2, 3],
  [4, 5, 6]
];

// Function to update and display the 'result'
function updateAndDisplayResult() {
  // Loop through your data and populate the table
  my_array.forEach(function(subArray) {
    var row = $('<tr>'); // Create a row for each sub-array

    subArray.forEach(function(item) {
      var cell = $('<td>').text(item);
      cell.css('border', '1px solid black'); // Add cell border
      row.append(cell);
    });

    tableContainer.append(row); // Append the row to the table
  });

  // Finally, append the tableContainer to your document
  $('#result').append(tableContainer);
};

window.addEventListener('scroll', handleScroll)

updateAndDisplayResult();
<div id="result"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

I’ve attached a few pictures to better clarify as well:

Wrong Scroll bar affects window.scrollY

Scroll always enabled by default

I’ve tried many things, but I’m stuck here. Any solutions to the following would be greatly appreciated:

  1. Link table scroll bar scrolly to window.scrollY value
  2. Hide scroll bar until the max-height defined.

Thanks in advance for any help!

My Cordova Splash Screen not working on Android

I am building an app using Cordova. Every other thing works but the Splash Screen.
Has anyone used it lately?
Here is my code:
config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloWorld</name>
    <description>Sample Apache Cordova App</description>
    <author email="[email protected]" href="https://cordova.apache.org">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    
    <platform name="android">
        <preference name="SplashScreen" value="screen" />
        <preference name="SplashScreenDelay" value="3000" />
        <preference name="SplashMaintainAspectRatio" value="true" />
        <icon density="ldpi" src="res/icon/android/icon-36-ldpi.png" />

        <!-- Use the AndroidWindowSplashScreen preferences for splash screen configurations -->
        <preference name="AndroidWindowSplashScreen" value="screen" />
        <preference name="AndroidWindowSplashScreenAnimationDuration" value="2000" />
        <preference name="AndroidWindowSplashScreenContent" value="res/screen/android/land-ldpi.png" />
        <!-- Add more splash screen configurations for other densities -->
    </platform>
</widget>

Here is my file structure
projectRoot
platforms
plugins
www
res
screen
android
land-ldpi.png
ios

its not working. It keeps showing the default cordova icon as shown in the image below
enter image description here

Any idea what i can try, i have followed almsot all resource i can find online. Any guide that can help in 2023 i would appreciate

How to log specific text in an ul?

I cannot figure out how to console log the innerText inside of the li and not the p that is nested inside of the li.

HTML

<ul id="list">
    
      <li>Tank
        <p>this is tank</p>
      </li>
    
    
      <li>Warrior
        <p>this is warrior</p>
      </li>
    
    
      <li>Ninja
        <p>this is ninja</p>
      </li>
    
  </ul>

JavaScript

const listChoice = document.querySelectorAll('li')

listChoice.forEach(cls => {
  cls.addEventListener('click', (e) => {
    const choice = e.target.innerText

    console.log(choice)

    if (choice === 'Tank') {
      console.log('You chose tank')
    }
  })
})

I can’t get my choice variable to equal the target innerText so that the console.log(‘you chose tank’) shows in the console.

I’ve tried using firstChild and it logs “Tank “

Three.js Project not loading

I am currently learning how to develop apps with Three.js in class.
I have some templates from my teacher who work 100%.
I have had other simpler projects work just fine, with this one, when i run the Five Server on VS Code everything that has to do with THREE js just doesent work, the imports are correct, and the installment of three js is fine ( I re-instaled just in case).
The HTML i am trying to run with the five server has the following imports

<script type="importmap">
    {
        "imports": {
            "three":"../three.js-master/build/three.module.js",
            "three/addons/":"../three.js-master/examples/jsm/"
        }
    }
<script type="module">
    import * as THREE from "three";
    import Orientation from "./orientation.js";
    import ThumbRaiser from "./thumb_raiser_template.js";

Every thing was sent by my teacher and runs on my peers computers, i just cant figure out what i am doing wrong. The three.js folder is one fodler before the actual project.

In html, can a style command be dynamically changed by a script? [duplicate]

Trying to either display a line of data or not depending on the contents of an input field

The contents of an output line are built like the following:

document.getElementById("obstacle").innerHTML = o50_oat+'xB0 C, xa0xa0 '+o50_g+' gal';

Then a style command is generated like this:

if(o50_g == 0.0)
   document.getElementById("obstaclestyle").innerHTML = "display:none";
else
   document.getElementById("obstaclestyle").innerHTML = "";

The intent is that when o50_g == 0.0, the following, in the html, causes nothing to be displayed.

  <span style=<span id="obstaclestyle"></span>    
  <span style="color:green"><span id="obstacle"></span></span><br><br><br><br><br>
  </span>

and when 050_g != 0.0, the above will actually display the line

Instead the above displays:

display:none 0° C, 0 gal, 0 min, 0 sec, 0 ft

with the data in green

I tried various combinations of punctuation for display:none but none of them worked. They either caused no data to be output or display:none is just seen as text like the above.

Is what I am trying to do possible with the right syntax

How to split document array into multiple arrays by grouping them?

I’m trying to create a kind of chat. All messages are stored in a “messages” collections and look like this:

[
    {
        content: 'content 1',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T19:57:42.124Z")
    },
    {
        content: 'content 2',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T19:58:42.124Z")
    },
    {
        content: 'content 3',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T19:59:42.124Z")
    },
    {
        content: 'content 4',
        userId: '345',
        targetUserId: '123',
        timestamp: ISODate("2023-11-06T20:00:42.124Z")
    },
    {
        content: 'content 5',
        userId: '345',
        targetUserId: '123',
        timestamp: ISODate("2023-11-06T20:01:42.124Z")
    },
    {
        content: 'content 6',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T20:02:42.124Z")
    },
    {
        content: 'content 7',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T20:03:42.124Z")
    }
]

I need to group this content by userId and timestamp: Of course the messages should be sorted by timestamp. So far this is no big deal. But I also need to group the messages by userId. In this example the user 123 posted three messages – which will be displayed on the left side. The user 345 then answered with two messages – which will be displayed on the right side. And finally the first user again posted two messages.

[
    {
        content: 'content 1',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T19:57:42.124Z")
    },
    {
        content: 'content 2',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T19:58:42.124Z")
    },
    {
        content: 'content 3',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T19:59:42.124Z")
    }
], [
    {
        content: 'content 4',
        userId: '345',
        targetUserId: '123',
        timestamp: ISODate("2023-11-06T20:00:42.124Z")
    },
    {
        content: 'content 5',
        userId: '345',
        targetUserId: '123',
        timestamp: ISODate("2023-11-06T20:01:42.124Z")
    }
    ], [
    {
        content: 'content 6',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T20:02:42.124Z")
    },
    {
        content: 'content 7',
        userId: '123',
        targetUserId: '345',
        timestamp: ISODate("2023-11-06T20:03:42.124Z")
    }
]

I do get the relevant documents by doing

Messages.find().sort({ timestamp : 1 })

But I don’t get it how to create the multiple arrays for each messages “block”