Cannot read properties of Object, still can read Object tho(vue.js)

js project and i face an unexpected problem.

I tried to read one of properties of a Object, but i can’t while the object is available to read.

this is my code to read object.

let p = this.contentList[this.contextMenuIndex];
        console.log(p)

and this is the result.
enter image description here

but when i try to read property,
console.log(p.id);

enter image description here

what’s wrong with this problem?

somebody can help me?

OS : windows 11
language : js
library : vue3.2.23

Can I destructure object refs in Vue 3 Composition API?

I want to destructure a reactive object into refs so I don’t need to use the full object path to access them in the code/template.

Given an object like this:

const exampleStuff = ref({ 
  house: { doors: 2, windows: 6 }, 
  car: { doors: 4, windows: 8 }
});

// ...and update the object to test reactivity
setTimeout(() => {
  exampleStuff.value = { 
    house: { doors: 1, windows: 5 }, 
    car: { doors: 2, windows: 6 } 
  };
}, 2000);

In this simplified example, I’d like to assign a variable, car, so that I can access its reactive value directly.

I tried a few things, and they didn’t work as expected:

// printing {{ car.windows }} in the template stays as 8,
// even when the value updates to 6
const car = exampleStuff.value.car;

// same if I wrap it in toRef: {{ car.windows }} stays as 8
const car = toRef(exampleStuff.value.car);

A computed getter does work, however:

// printing {{ car.windows }} in the template updates from 8 to 6 as expected
const car = computed(() => exampleStuff.value.car);

I know computed getters would be the only solution in the Options API, but I thought there was a way to do this in the Composition API.

Is there a way to destructure objects with the Vue 3 Composition API, and keep their reactivity?

Is this the right way to update a object in an array?

I have this code:

        vg = vg.map((vari => {
            if(vari.option1 === el.option1) {
                return {
                    ...vari,
                    variantId: [...vari.variantId, el.variantId],
                    images: ss?.image ? [...vari.images, ss.image] : [...vari.images]
                }
            } else {
                return {
                    ...vari
                }
            }
        }))

And I want it to rewrite this with for loop

is this right and immuteable ?

        for(let g = 0; g < vg.length; g++) {
            if(vg[g].option1 === el.option1) {
                vg[g].variantId = [...vg[g].variantId, el.variantId];
                vg[g].images = ss?.image ? [...vg[g].images, ss.image] : [...vg[g].images]
            }
        }

if is not please help me to say me what I did wrong. Its work but is this right way to update an array of object ?

How do you display a webcam feed in GLSL, using Three.js?

There are multiple examples on how to display a webcam video using ThreeJS by creating a video texture like so :

video = document.getElementById( 'video' );
const texture = new THREE.VideoTexture( video );
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.MeshBasicMaterial( { map: texture } );
const geometry = new THREE.PlaneGeometry(1, 1);
const plane = new THREE.Mesh(geometry, material);
plane.position.set(0.5, 0.5, 0);

Where the video is an html element that plays the webcam’s feed. But the problem is I can’t access the feed and play with it using fragment shaders!

How can I manipulate the webcam’s video feed in my shader files? I have the materials for my shader files defined like so :

const vsh = await fetch('vertex-shader.glsl');
const fsh = await fetch('fragment-shader.glsl');
material = new THREE.ShaderMaterial({
  uniforms: {
    resolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) },
    time: { value: 0.0 },
  },
  vertexShader: await vsh.text(),
  fragmentShader: await fsh.text()

Any ideas or simple examples that show that?

Error when playing notification sound without user interaction on modern browsers

In my reactjs app I am playing an audio when receiving a websocket message:

  const playSound = () => {
    if (audioRef.current) {
      audioRef.current
        .play()
        .then(() => {})
        .catch((error) => {
          console.error("Audio playback error:", error);
        });
    }
  };

  const handleClick = () => {
    const element = document.getElementById("audioButton");
    if (element) {
      element.click();
    }
  };

  useEffect(() => {
    socket.on("receive_message", (data) => {
      if (data && data.action === "play_sound") {
        handleClick();
      }
      fetchOrders();
    });

    return () => {
      socket.off("receive_message");
    };
  }, []);
      <audio ref={audioRef}>
        <source src="/audio/sound.mp3" type="audio/mpeg" />
        Your browser does not support the audio element.
      </audio>
      <button
        id="audioButton"
        style={{ display: "none" }}
        onClick={() => playSound()}
      />

When the user is interacting with the website the audio plays correctly, but when the user is in another tab or did not interact with the website for a while, this error is being thrown (edge, chrome, latest versions):

Audio playback error: DOMException: play() failed because the user didn't interact with the document first.

In Firefox:

Audio playback error: DOMException: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

I know that modern browsers prevent audios from being played automatically but since I am working on a chat application with a user notification feature, I am looking for a workaround.

The reason why I am triggering a click event when receiving a websocket message instead of directly playing the audio is to simulate a user interaction, but this does not fix the issue.

I know there are similiar questions but none of them provides a working solution for this issue.
Is there any way to bypass this?

I tried to simulate a user interaction with a click event instead of playing the audio directly which did not solve the issue.

I can’t get res.status.json message in alert

I was trying to get res.status.json as an alert, but what I could only get was this;

result

this is my Server join.js

const express = require('express');
const mongoose = require('../mongoose/index');
const router = express.Router();
const Customer = require("../mongoose/schemas/customers");
const crypto = require('crypto');

mongoose.connect();

router.get("/", function (req, res,) {
    fs.readFile("./views/join.html", (err, data) => {
        if (err) {
            res.send("error");
        } else {
            res.writeHead(200, { "Content-Type": "text/html" });
            res.write(data);
            res.end();
        }
    });
});

//Check duplicated id
router.post('/duplicated', async (req, res) => {
    try {
        const { userid } = req.body;
        const existingUser = await Customer.findOne({ userid });

        if (existingUser) {
            return res.json({ exists: true });
        } else {
            return res.json({ exists: false });
        }
    } catch (error) {
        console.error(error);
        return res.status(500).json({ message: 'Server Error' });
    }
});

// Registeration
router.post("/", async (req, res) => {
    try {
        const { userid, userpw } = req.body;

        const hashedPassword = crypto.createHash('sha512').update(userpw).digest('hex');

        const newCustomer = new Customer({ userid, userpw:hashedPassword });
        await newCustomer.save();
        
        
        return res.status(201).json({ message: 'Join Completed' });
        //res.status(201).redirect("/login");
        
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: "Server Error" });
    }
});

module.exports = router;

and this is my client join.js

const userid = document.querySelector("#userid"),
    userpw = document.querySelector("#userpw"),
    userpwc = document.querySelector("#userpwc"),
    matchMessage = document.getElementById('password-match-message'),
    registrationButton = document.querySelector("#SignupButton"),
    idCheck = document.querySelector("#idcheck"),
    userIdWarning = document.querySelector("#userIdWarning");
    
        
userpwc.addEventListener('input', confirmpw);
idCheck.addEventListener("click", checkDuplicateID);

//Registration
async function register(){

    const newUserId = userid.value;
    const newPassword = userpw.value;
    const newPasswordc = userpwc.value;

    try {
        // 회원가입 요청
        const response = await fetch('/join', {
            method: 'POST',
            headers: {
            'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userid: newUserId,
                userpw: newPassword
            })
        });
    
            const data = await response.json();
            console.log(data);
            console.log(data.message);
            if (data.message === 'Join Completed') {
                alert(data.message);
                setTimeout(function() {
                window.location.href = "/login";
                }, 5000);
            } else {
                // if join failed
                console.error('Login Failed:', data.message);
            }
        } catch (error) {
        console.error('Error:', error);
        }
}

// check pw
function confirmpw() {
    let value1 = userpw.value;
    let value2 = userpwc.value;

    if (value2 !== "") {
        if (value1 === value2) {
            matchMessage.textContent = "Match";
            matchMessage.style.color = "#4caf50";
        } else {
            matchMessage.textContent = "Doesn't Match";
            matchMessage.style.color = "#f44336";
        }
    } else {
        matchMessage.textContent = "";
    };
}

function checkDuplicateID() {
    const newUserId = userid.value;
    const regexs = /^(?=.*[a-zA-Z])[a-zA-Z0-9]{1,}$/;
    
    
        if (!newUserId) {
        idCheck.innerText = "Type your id";
        return;
        }
    
        if (!regexs.test(newUserId)) {
        idCheck.innerText = "Invalid id";
        return;
        }
    
        // check duplicated id
        fetch('/join/duplicated', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ userid: newUserId })
        })
        .then(response => response.json())
        .then(data => {
            const userIdWarning = document.getElementById('userIdWarning');
            // if duplicated
            if (data.exists) {
            userIdWarning.innerText = "Unavailable ID";
            registrationButton.disabled = true;
            } else {
            userIdWarning.innerText = "Available ID";
            // not duplicated
            registrationButton.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }

plus, I could make endpoint of fetch(‘/join/duplicated’, by the way, it was impossible to make endpoint of /join/register. When I tried to Post registeration by fetch(‘/join/register’, and then console printed POST join/404

Console

Thank you.

How do I scrape website that uses AJAX to dynamically load info?

I’ve been trying to scrape CalDining(UC Berkeley’s dining hall website– https://dining.berkeley.edu/menus/) but the item nutritional information for each menu item loads dynamically in a popup when it is clicked on. However, even when I use chrome driver to click on the items, I do not get the new loaded information. When I look behind the HTML at the network, it is pulling from another url: https://dining.berkeley.edu/wp-admin/admin-ajax.php. Although this URL is always the same, the content behind it is changing. When you click on payload, it shows the specific id and menuid that are associated with the menu item. I also noticed that the request method is ‘POST.'(dont know if that has anything to do with it but just wanted to put it out there). I’ve posted a couple photos below. Please let me know if there is a good way to do this.[enter image description here](https://i.stack.imgur.com/H41L6.png)[enter image description here](https://i.stack.imgur.com/bjBSG.png)
enter image description here

This is what I have tried but it has not worked: it prints out nothing because the information has not loaded.

With the use of Jquery, how to target CSS selectors with the exception of one class?

Here is an example of the HTML:

<div class="DataBox">
  <div class="diagram">
    <h3 class="dataNumber">
      Artificial intelligence is the intelligence 
        of machines or software, as opposed to the 
        intelligence of humans or animals.
      <span class="subDataTitle">
        AI augments human intelligence with rich analytics
      </span>
    </h3>
  </div>
</div>

I am trying to truncate the text underneath the .dataNumber to a certain character amount, but I don’t want to truncate any of the text in subDataTitle.

With how the HTML is structured, how would I write the code so that I’m only applying truncating logic to the text underneath dataNumber but not to the text in subDataTitle .

This is how I approached it using the :not, but it doesn’t seem to work:

$('.DataBox .diagram .dataNumber:not(.DataBox .diagram .dataNumber.subDataTitle)')
  .each(function (index, value) {
    var dataLength = $(this).text().length;
    if (dataLength > 8) {
      $(this).html($(this).html().substring(0, 12) + ' ...');
    }
  });

Nextjs App Router Set Global Axios Instance Bearer Token

I have a turborepo with two nextjs apps (web and admin) along with a shared packages directory. In this directory I want to create a shared axios instance for both apps to use. How can I set the authorization header in the axios instance?

For example:

/apps/web/middleware.ts

import { getToken } from "next-auth/jwt";
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";

export default withAuth(
  async function middleware(req) {
    const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });

    const requestHeaders = new Headers(req.headers);

    requestHeaders.set('authorization', `Bearer ${token["idToken"]}`);

    return NextResponse.next({
      request: {
        headers: requestHeaders,
      },
    });

  },
  {
    callbacks: {
      authorized: ({ token }) => {
        if (token) {
          return true;
        }
        return false;
      }
    },
  }
);

export const config = { matcher: ["/"] };

This code sets the correct bearer token for each subsequent request. The problem is my axios instance is defined in

/packages/app/lib/axios.ts

import axios from "axios";
import { headers } from "next/headers";

const headersInstance = headers();
const authorization = headersInstance.get('authorization');

export const axiosInstance = axios.create({
    baseURL: "http://localhost:7112/api/",
    timeout: 1000,
    headers: { authorization } ===> this does not work, header is null
});

How can I get the authorization header in the instance without having to set it for each call?

React-Bootstrap Overlay with Popup doesn’t work

I was trying to use React-Bootstrap’s overlay with Popup.

Here is their example:

import { useState, useRef } from 'react';
import Button from 'react-bootstrap/Button';
import Overlay from 'react-bootstrap/Overlay';
import Popover from 'react-bootstrap/Popover';

function Example() {
  const [show, setShow] = useState(false);
  const [target, setTarget] = useState(null);
  const ref = useRef(null);

  const handleClick = (event) => {
    setShow(!show);
    setTarget(event.target);
  };

  return (
    <div ref={ref}>
      <Button onClick={handleClick}>Holy guacamole!</Button>

      <Overlay
        show={show}
        target={target}
        placement="bottom"
        container={ref}
        containerPadding={20}
      >
        <Popover id="popover-contained">
          <Popover.Header as="h3">Popover bottom</Popover.Header>
          <Popover.Body>
            <strong>Holy guacamole!</strong> Check this info.
          </Popover.Body>
        </Popover>
      </Overlay>
    </div>
  );
}

export default Example;

I tried the following:

import React, { useRef, useState } from "react";
import { Overlay, Popover } from "react-bootstrap";

const SimpleMRE: React.FC = () => {
    const container = useRef(null)
    const [target, setTarget] = useState<HTMLElement | null>(null)
    const [show, setShow] = useState(false)
    const timeout = useRef<NodeJS.Timeout | undefined>()

    function onMouseOut(e: React.MouseEvent): void {
        timeout.current = setTimeout(() => {
            setShow(false)
        }, 1500)
    }

    function onMouseOver(e: React.MouseEvent): void {
        if (timeout.current) {
            clearTimeout(timeout.current)
        }

        setTarget(e.target as HTMLElement)
        setShow(true)
    }
    
    return (
        <div ref={container}>
            <a onMouseOver={onMouseOver} onMouseOut={onMouseOut} href="www.google.com">Link to my resource</a>

            <Overlay show={show} target={target} placement="top" container={container} containerPadding={20}>
                <Popover id="testPopover">
                    <Popover.Header>Some lovely header</Popover.Header>
                    <Popover.Body>Some lovely body</Popover.Body>
                </Popover>
            </Overlay>
        </div>
    )
}

export default SimpleMRE

However, when I hover over the link, nothing happens at all – the popup doesn’t appear and nothing is displayed in the console.

Even when I use code that’s essentially identical to their example, nothing happens:

import React, { useRef, useState } from "react";
import { Button, Overlay, Popover } from "react-bootstrap";

const SimpleMRE: React.FC = () => {
    const [show, setShow] = useState(false);
    const [target, setTarget] = useState(null);
    const ref = useRef(null);

    const handleClick = (event: any) => {
        setShow(!show);
        setTarget(event.target);
    };

    return (
        <div ref={ref}>
            <Button onClick={handleClick}>Holy guacamole!</Button>

            <Overlay
                show={show}
                target={target}
                placement="bottom"
                container={ref}
                containerPadding={20}
            >
                <Popover id="popover-contained">
                    <Popover.Header as="h3">Popover bottom</Popover.Header>
                    <Popover.Body>
                        <strong>Holy guacamole!</strong> Check this info.
                    </Popover.Body>
                </Popover>
            </Overlay>
        </div>
    );
}

export default SimpleMRE;

I am able to use other React-Bootstrap components just fine. In fact, if I try to use their Popup with no Overlay, it works just fine; however, I can’t do that because it covers the text, which I don’t want, and the documentation says that I need to use an overlay in order to be able to place it.

I’m at somewhat of a loss as to what to try next, or even how to debug this further. Does anyone have suggestions as to how I can fix this?

facing problems related to images slides in web dev html css js [closed]

I’m encountering an issue where the images I’ve placed inside a carousel’s slide elements () aren’t displaying, although they show up perfectly outside the carousel section. I’ve ensured that the file paths to the images are correct and checked the HTML structure, CSS styling, and JavaScript logic, but the images still don’t appear within the carousel. Could someone assist in identifying why the images aren’t showing up within the carousel’s slides despite being correctly placed?
enter image description here

Conditionally add attribute to HTML tag

I have an anchor tags with some attributes but I need to add an attribute based on some attribute.
For example –

     <a
        
        className={someName}
        onContextMenu={handleClick}
      >

I need onContextMenu to be present only if some condition is true. Something like this –

     <a
        
        className={someName}
        if (true) ? onContextMenu={handleClick} : ''
      >

How can I achieve it? Coding in Typescript.

Office JS – Italic between quotation marks

Beginer here.

My problem might be basic but I am struggling to find a way to solve it.

I’m developing a Word add-in using the Office JS API. I want a function that will put any text between quotation marks in italics, but I don’t want the quotation marks themselves in italics.

I know how to find text between quotation marks, but I don’t know how to exclude the quotation marks from my range. I tried unsuccessfully using the slice method.

Do you have any idea how to achieve this?

async function run() {
  await Word.run(async (context) => {
    const body = context.document.body;
    const searchResultsQuotationMarks = body.search(String.fromCharCode(0x00ab) + "*" + String.fromCharCode(0x00bb), {
      matchWildcards: true
    });

    searchResultsQuotationMarks.load("text, font");
    await context.sync();


    searchResultsQuotationMarks.items.forEach((resultQuotationMarks) => {

      const text = resultQuotationMarks.text.slice(1, -1);


      const font = resultQuotationMarks.font;
      font.italic = true;
    });

    await context.sync();
  });
}

Thanks!

How to trigger useSprings() multiple animations, back to back

First started animating using @react-spring/three‘s useSpring(), and then got useSprings() working, but only for one animation at a time still.

  1. How do I queue one animation after another?
  2. Is there a better way to detect when an animation is done than .idle and !.isAnimating?
  3. How to avoid manually queueing the animations?

Currently viewable at https://demo.robotjs.org/

Setup Springs:

const [springs, api] = useSprings(
  1,
  () => ({
    jointAngles: jointAngles,
    config: {
      easing: easings.easeInOutQuad
    }
  }),
  []
)

Start a robot animation:

api.start({
  jointAngles: randomJointAngles()
})

Check if it is done:

if ( springs[0].jointAngles.idle ) {
  // end animation trigger
}

This is how I think it should be setup, but not sure how to trigger the different moves move[i] without api.start().

const moves = [
  ...
]

const [springs, api] = useSprings(
  moves.length,
  i => (
    {
      jointAngles: moves[i],
      config: {
        easing: easings.easeInOutQuad
      }
    }
  ),
  []
)