React page is not showing when there is an error, is there any method that we can use to see the actual error?

React page is not showing when there is an error, is there any method that we can use to see the actual error.

trying to built a simple game on the base of react. that work like lottery ticket

import { getTicket, sum } from "./helper";
import "./Lottery.css";
import { useState, useEffect, useRef } from "react";
import party from "party-js";

export default function Lottery() {
    let [ticket, setTicket] = useState(getTicket(3));
    let isWining = sum(ticket);
    const winnerRef = useRef(null);

    useEffect(() => {
        if (isWining === 15) {
            party.confetti(winnerRef.current, {
                count: party.variation.range(60, 90),
            });
        }
    }, [isWining]);
    
    let newTicket = () => {
        setTicket(getTicket(3));
    }

    return (
        <div>
            <div>
                <h1>This is a lottery game</h1>
            </div>
            <div className="Ticket">
                <span>{ticket[0]}</span>
                <span>{ticket[1]}</span>
                <span>{ticket[2]}</span>
            </div>
            {isWining === 15 ?
                <p ref={winnerRef}>Winner</p> :
                <p>Loser</p>}
            <div>
                <button onClick={newTicket}>Buy New Ticket</button>
            </div>
        </div>
    )
}

this is my code but not worked

How to implement proper cart logic?

The cart behaves incorrectly: When adding a product for the first time, only its quantity is displayed, the image and ID are not transmitted, I tried to find out the value of the ID that is transmitted when adding the first product via console.log and it returned null, but if I add another product to the cart it is displayed correctly. PRODUCT.HTML:

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', () => {
      // Получение данных о продукте
      const urlParams = new URLSearchParams(window.location.search);
      const productId = urlParams.get('id');

      if (productId) {
        fetch(`/product/${productId}`)
          .then(response => response.json())
          .then(product => {
            const buttonsContainer = document.getElementById('buttonsContainer');

            document.getElementById('product-name').textContent = product.name;
            document.getElementById('price').textContent = `Цена: ${product.price}`;
            document.getElementById('short-sub').textContent = product.short_description;
            document.getElementById('productDescription').textContent = product.description;
            document.getElementById('article').textContent = `Артикул: ${product.article}`;
            document.getElementById('volume').textContent = `Объем: ${product.volume}`;
            document.getElementById('points').textContent = `Баллы: ${product.points}`;
            document.getElementById('productImage1').src = `images/${product.image_2_url}`;
            // Дополнительно можете добавить код для изображения и других данных

            buttonsContainer.innerHTML = `
                <a href="order.html"><button class="buy-button"><b>КУПИТЬ</b></button></a>
                <button class="cart-button" data-product-id="${product.id}" data-image-url="${product.image_url}"><b>В КОРЗИНУ</b></button>
              `;
            
            // Добавление товаров в корзину
            const addToCartButtons = document.querySelectorAll('.cart-button');

            addToCartButtons.forEach(button => {
              button.addEventListener('click', (event) => {
                const imageUrl = event.target.getAttribute('data-image-url');
                addToCart(productId, imageUrl);
              });
            });
          })
          .catch(error => {
            console.error('Error fetching product data:', error);
          });
      }
    

    function addToCart(productId, imageUrl) {
  let cart = JSON.parse(localStorage.getItem('cart')) || [];
  let productExists = false;

  cart.forEach(item => {
    if (item.id === productId) {
      item.quantity += 1;
      productExists = true;
    }
  });

  if (!productExists) {
    cart.push({ id: productId, quantity: 1, image: imageUrl });
  }

  localStorage.setItem('cart', JSON.stringify(cart));

  alert('Товар добавлен в корзину');
}

    });
</script>

CART.HTML:

<script type="text/javascript">
            document.addEventListener('DOMContentLoaded', () => {
  displayCart();
});

function displayCart() {
  const cart = JSON.parse(localStorage.getItem('cart')) || [];
  console.log('Loaded cart:', cart); // Добавлено логирование

  const cartContainer = document.getElementById('cart-container');

  cart.forEach(item => {
    const productElement = document.createElement('div');
    productElement.className = 'product';
    productElement.innerHTML = `<div class="q"><b><p>${item.quantity}</p></b></div><img src="${item.image || 'images/default.png'}">`; // Указано изображение по умолчанию
    cartContainer.appendChild(productElement);
  });
}

        </script>

Here is the logic that should be instead: I add product 1 to the cart, which was empty, then in the cart I see this product with quantity 1, when I add this product again, the quantity increases, then I add product 2 to the cart where there is already product 1 , I go to the cart and see product 1 and product 2 with different quantity values ​​and so on.

Medusa.JS – req.body empty in POST middleware

Pulling my hair out over this. Thanks in advance to anyone who can take a look. Any idea why req.body would be empty? Medusa.JS should be using bodyParser by default, yes? It was working earlier today and now it isn’t. Clearly something has changed and I can’t figure out what. This is my middlewares.ts file:

async function myTestFunc(req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) {
  const logger = req.scope.resolve<Logger>('logger');
  console.log("Request BODY!", JSON.stringify(req.body))
  console.log("Request PARAMS!", JSON.stringify(req.params))
  console.log("Customer ID!", JSON.stringify(req.user?.customer_id))
  next();
}

export const config: MiddlewaresConfig = {
  routes: [
    {
      matcher: '/store/carts/:id/line-items',
      middlewares: [authenticateCustomer(), myTestFunc]
    }
  ],
};

Thanks again, much appreciated.

how i can fit the html title tag for lengthy content

I’m having trouble with the HTML title tag for lengthy content since it keeps cutting the content off the screen. is there a way to fit text on the screen or is there another option that functions similarly to a tooltip?

<h1 title="
test 1
           
test 2
           
test 3
           
test 4
           
test 5
           
test 6
           
test 7
           
test 8
           
test 9
           
test 10
           
test 11
           
test 12
           
test 13
           
test 14
           
test 15

test 1
           
test 2
           
test 3
           
test 4
           
test 5
           
test 6
           
test 7
           
test 8
           
test 9
           
test 10
           
test 11
           
test 12
           
test 13
           
test 14
           
test 15
           
test 1
           
test 2
           
test 3
           
test 4
           
test 5
           
test 6
           
test 7
           
test 8
           
test 9
           
test 10
           
test 11
           
test 12
           
test 13
           
test 14
           
test 15
">Tooltip</h1>

How do i loop through divs using jsoup in groovy script

My requirement is to scrap all the review data like reviewer name, date and comment in array. That i am doing in mulesoft in groovy script by importing Jsoup.

Using below query i am able to fetch the review data but it’s coming in a single string. Not sure how to separate the div tag here.
Please inspect the mentioned url and please suggest how i can run a loop on <div class=”Jwxk6d” and make the expected output.

code:

    import org.jsoup.Jsoup
    def url= "https://play.google.com/store/apps/details?id=at.bitfire.davdroid&hl=en_IN"
    def doc= Jsoup.connect(url).get()
    def appReviewData= doc.select("div[class='EGFGHd']").text()
    return [ReviewData: appReviewData]
    
    

expected output:

    {
        "ReviewData": [{
            "name": "Ben Perkins",
            "reviewDate": "7 June 2024",
            "reviewComment": "xyz"
        }]
    }

Getting issue while passing _id to find an existing item

Creating a job portal website using react and mongodb. A user logins and save the job. So a model is created to save the jobs and created Controller. Before saving a job checks if it is exist or not by passing the _id which fetched from the req.params and the userId which from the req.payload . But it doesn’t checks the existingJob and creating it as a new object.

exports.savedJobsController = async (req,res) =>{

console.log("Inside Saved Jobs Controller");



const {title,salary,email,company,location,description,category,jobType,experience,vacancy,deadline} = req.body



const {id} = req.params



const userId = req.payload



console.log(user id is : ${userId} and id is ${id});



try {



    const existingJob = await savedjobs.findOne({_id:id,userId})



    console.log(exist ${existingJob});



    if(existingJob){



        res.status(406).json("Job Already Saved to Your Collection!")



    }else{



        const newJob = new savedjobs({



            title,salary,email,company,location,description,category,jobType,experience,vacancy,deadline,userId



        })



        await newJob.save()



        res.status(200).json(newJob)



        console.log(Saved job is 



            ${newJob}



            );



    }



    



} catch (error) {



    res.status(401).json(error)



    console.log(error);



}

}

Discord js gives me “DiscordAPIError: Cannot send an empty message” when I put “async, await” in the script

When a user sends a fur file with “$fur2mp3”,
the bot has to download it to the local repository,
convert it through an external batch script,
and send the converted file to a channel.

but an asynchronous problem causes the bot to run the script in the middle of downloading the sent file so display it as an empty file…

So I tried to solve the problem using await and async, but every time I do, I get this error

C:UsersUserDocumentsDiscord-CommandLine-1.0.1node_modulesdiscord.jssrcrestRequestHandler.js:154
      throw new DiscordAPIError(request.path, data, request.method, res.status);
            ^

DiscordAPIError: Cannot send an empty message
    at RequestHandler.execute (C:UsersUserDocumentsDiscord-CommandLine-1.0.1node_modulesdiscord.jssrcrestRequestHandler.js:154:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async RequestHandler.push (C:UsersUserDocumentsDiscord-CommandLine-1.0.1node_modulesdiscord.jssrcrestRequestHandler.js:39:14) {
  method: 'post',
  path: '/channels/(hidden channel ID)/messages',
  code: 50006,
  httpStatus: 400
}

Node.js v20.16.0

The script is

commands.add('fur2mp3', async () => {
      const filePath = 'buffer_furrendering.txt';
    
    if (fs.existsSync(filePath)) {
        msg.channel.send('Another file is being processed! Please wait!');
        return;
    }
        if(msg.attachments.first()){//checks if an attachment is sent
            //if(msg.attachments.first().filename === `fur`){
                msg.channel.send('Uploading...');
                await download(msg.attachments.first().url);
                msg.channel.send('Uploaded!');
                //msg.channel.send('d');
                msg.channel.send('Current Furnace Tracker Version : 0.6.5nConverting started!');
                msg.channel.startTyping();
                exec('fur2wav.bat buffer_furinput.fur', (error, stdout, stderr) => {
                    if (error) {
                        msg.channel.send(`Error during conversion: ${stderr}`);
                        console.error(`Conversion error: ${stderr}`);
                        return;
                    }
                    fs.readFile('buffer_fur2wavmsg.txt', 'utf8', (err, gwav) => {
                    if (err) {
                        msg.channel.send('Error reading conversion message.');
                        console.error(err);
                        return;
                    }
                    console.log('gwav content:', gwav);  // Log content
                    if (gwav.trim()) {  // Ensure gwav is not empty
                        
                    } else {
                        msg.channel.send('The conversion did not produce any output.');
                    }
                    msg.channel.send({ files: ["furoutput.mp3"] });
                }); 
                });
                
    
            
        } //msg.channel. // 파이 이름 ㅍbuffer_furinput.fur'
               else { msg.channel.send('Send your file with this command!');
               return; }
});

I need to remove await and async from here to proceed without error (though of course nothing is converted)

is there a mistake?

creating a boolean evaluator in javascript

i have some text like

text = "this is some text that have a bunch of words in it."

I have a boolean expression that will run against that text, for example:

boolPhrase = "(text OR keyword) AND (words OR keyword2)"

in this scenario, it would evaluate to be (true OR false) AND (true OR false) –> which evaluates to be true

so if I had the function that handles this logic

result = booleanEvaluator(text, boolPhrase)

I was able to do this using .eval() but I didn’t realize chrome blocks eval most of the time.

is there a javascript library that handles this kind of thing? or do I need to write this from scratch?

building a boolean interpreter in javascript

i need to ask a question in stack overflow

i have some text like

text = "this is a blob of text that have a bunch of words in it."

then I have a boolean expression that will run against that text, for example:

boolPhrase = "(blob OR keyword) AND (words OR keyword2)"

in this scenario, it would evaluate to be (true OR false) AND (true OR false) –> which evaluates to be true

so if I had the function that handles this logic

result = booleanEvaluator(text, boolPhrase)

I was able to do this using .eval() but I didn’t realize chrome blocks eval most of the time.

is there a javascript library that handles this kind of thing? or do I need to write this from scratch?

How to get the httprequest result from Xslist search url in Tampermonkey?

I want to get the Xslist result, but it seems to be forbidden to request, and it shows this in the console.

I use this in Tampermonkey by the GM_xmlhttpRequest

    GM_xmlhttpRequest({
         method: 'GET',
         url: 'https://xslist.org/search?query=%E7%AF%A0%E5%AE%AE%E8%8A%B1%E9%9F%B3&lg=zh',
         onload: function (result) {
             // xhrResult = result.status;
             let domNewx = new DOMParser().parseFromString(result.responseText, 'text/html');
             console.log(domNewx)
         }
     });

If I use HttpRequest, it will show Cross-domain

                         const Http = new XMLHttpRequest();
                         const url= 'https://xslist.org/search?query=%E7%AF%A0%E5%AE%AE%E8%8A%B1%E9%9F%B3&lg=zh';
                         Http.open("GET", url);
                         Http.send();
                         Http.onload = function(e) {
                            let domNewx = new DOMParser().parseFromString(Http.responseText, 'text/html');
                            console.log(domNewx)
                         }

The first result.
enter image description here

Xslist will show a real person verify page.

enter image description here

Updating the src attribute of the img tag in HTML results in overlapping with old images

I continuously send binary streams of images from the backend server to the frontend HTML page. After receiving the binary stream, the frontend HTML page uses the URL.nestObjectionURL function to convert it and directly applies it to the src attribute of the img tag, just like this

socket.onmessage = function (event) {
    document.getElementById('img').src = URL.createObjectURL(event.data)
}

I continuously display new images transmitted from the backend by updating the src attribute of the img tag
But new images will always be displayed overlaid with old images
enter image description here
This phenomenon is very strange. As long as my perspective remains in the current window, it will cause this. Once my perspective leaves the current page, it will return to normal. It seems that this situation occurs when I just look at this image. This is what happens when my perspective leaves the current page
enter image description here

Oh my god, I’m really going to crash. I’m a beginner in HTML and I can’t find any explanation for this phenomenon online. Can you please help me