Vue Child component loses reactivity to retrieved pinia/vueFire object

I am trying to load an item into a child component so I can edit the values. I am passing an itemId from the parent to the child as a prop and in the child I call a function store.itemForId(id) to retrieve the itemData from a vueFire/firstore collection. I can retrieve the item document in the child but it loses reactivity. If the firestore Document gets updated externally, the collection in the pinia store and the data in the parent gets updated but the item retrieved in the child does not.

However, if I use the same function in the parent and instead pass the item to the child, the reactivity stays.
This isn’t a solution because I will eventually need to be able to edit the item, but it makes me think the problem lies in the child somehow.

I’ve got a pinia store that gets a projectItems Collection and a projectInfo Document.

projectInfo.itemOrder gives the display order for the items.

// projectStore.js
const projectInfo = useDocument(() => doc(db, projectPath))
const { data:projectItems, promise:itemsPromise } = useCollection(() => collection(db, itemsPath))


function itemForId(id) {
  return projectItems.value.find((item) => item.id === id)
}

MyParent.vue

<script setup>
  import { useProjectStore } from 'stores/projectStore'

  const projectStore = useProjectStore()
  const { projectInfo, projectItems } = storeToRefs(projectStore)
</setup>
<template>

  <div>Child gets Id</div> <!-- not reactive -->
  <template v-for="itemId in projectInfo.itemOrder" :key="itemId">
    <IdChild :itemId="itemId" /> 
  </template>

  <div>Child gets Item</div> <!-- reactive -->
  <template v-for="itemId in projectInfo.itemOrder" :key="itemId">
    <ItemChild :item="projectStore.itemForId(itemId)" /> 
  </template>

  <div>Raw ItemData</div> <!-- reactive -->
  <div>{{ projectItems }}</div> 
</template>

IdChild.vue is not reactive

<script setup>
  import { useProjectStore } from 'stores/projectStore'
  
  const props = defineProps({ itemId: String })

  const projectStore = useProjectStore()
  const { projectItems } = storeToRefs(projectStore)

  // this seems to be where reactivity is lost. Tried with both ref and without.
  // console.log(item) shows it as a RefImpl / Proxy so it seems correct
  const item = ref(projectStore.itemForId(props.itemId))


</setup>
<template>

  <div>{{ item.name }}</div> <!-- not reactive -->
  
  <!-- this is reactive but seems wrong to have to do for every value -->
  <div>{{ projectStore.itemForId(itemId).name }}</div> 

  <div>Raw ItemData</div> <!-- for troubleshooting... but reactive too -->
  <div>{{ projectItems }}</div> 
</template>

ItemChild.vue – To troubleshoot I also made this which is reactive but since the item is passed as a prop it’s not editable.

<script setup>
  import { useProjectStore } from 'stores/projectStore'
  
  const props = defineProps({ item: Object })

</setup>
<template>

  <div>{{ item.name }}</div> <!-- reactive -->
  
</template>

How do I make a ref to the item in my child reactive?

Or is there something I am not understanding with how the reactivity works?

Issue with loading js library – unpkg.com v cdnjs.cloudflare.com – inside DOMContentLoaded event

I was having an issue that I was not able to use .insertString("Hello") method of Trix editor. I was 100% following instructions of official documentation https://github.com/basecamp/trix#inserting-and-deleting-text

I found out that the issue is the location of Trix library I was using.

If Trix is loaded from https://cdnjs.cloudflare.com everything works fine but unpkg.com

Could someone please explain how come such issue is happening of the code is inside DOMContentLoaded event? I thought that load event would solve it but the javascript code inserting text is not working with load event at all. Working jsFiddle

// document.addEventListener("load", function(event) {
 document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
     
     var element2 = document.querySelector("trix-editor")
     element2.editor  // is a Trix.Editor instance
     element2.editor.insertString("Hello2")
     
    });`enter code here`

React Native app not building due to mismatch between js and native codes and other potential issues

im stuck during 1 week now to simply build my react native app for my first project in a company, basically for android it said it has a mismatch between react native and native code versions, 0.61.3 and 0.64.4 basically, it said I could rebuild the native code to update it, i tried to run npx react-native run-ios and run-android but none of them worked because they didnt recognized a command I had to install, it was pod, i should do pod install, but to do this it requires an ubuntu password which i dont have because i use vs code inside the company’s server, my pc uses windows 11 but this virtual machine uses ubuntu… so i tried to forcelly change react native version to 0.64.4 and now the log error is not even showing in the app anymore, app is not building.

It says ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

probably because of the forced change but I dont know I just dont want to be kicked off in 1 week of my first project for an international client

I tried to npx react-native run-ios and run-android, i tried to install brew, pod, cocoapods, all of them required sudo command which requires a password which i dont and cannot have access.. My tech lead could not help me, the pm just wants the tasks to be done.. the other rn dev of the team couldnt help… so im asking you guys

im learning can someone explain me why this are happen in my code, many thanks in advance

setInterval(function(){
    let mostra = document.getElementById("mostrar");
    let contagem = ["5","4","3","2","1","..."];
    let ic = 0;
    let conta = contagem[ic];
    while(conta <= contagem.length){
        
        mostra.textContent = `algum texto  ${conta++}`;
    }
}, 1000);

and this not works and i try …

setInterval(function(){
    let mostra = document.getElementById("mostrar");
    let contagem = ["5","4","3","2","1","..."];
    for(let ic = 0; ic <= contagem.length; ic++){
        let conta = contagem[ic];
        mostra.textContent = `algum texto  ${conta++}`;
    }
}, 1000);

both failed im trying to redirect a user to home page and do 5, 4, 3, 2, 1, … and homepage

many thanks

someone to help me and explain what im doing wrong

Domain in cookie not being set properly after deploying but works in localhost

I am creating a full stack application using the MERN stack and I’m deploying it to render but when I try to send a cookie with the headers sameSite: “None”, secure: true, and domain: “.onrender.com” it does not set the cookie in the applications at all.

When I get rid of the domain header, the cookie is set but the domain is set to my backend url “backend-api.onrender.com” so my frontend “frontend.onrender.com” cannot read it. When I test it out using localhost everything works because the domain is localhost and both my frontend and backend are using that domain. Is there any way I can fix this issue?

How can I mute/unmute a microphone using WebRTC and PeerJs?

I’m trying to get the user to mute their microphone so that the other user on the call can’t hear them, but I’ve failed in every attempt.

I just wish the caller or callee could mute themselves so that one can’t hear the other.

This is my code:

if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ audio: true }).then(function(stream) {
        let currentCall = null;
        let remoteAudioElement = null;
        var localStream = stream;

        // Atender a chamada e fornecer a MediaStream
        peer.on('call', function(call) {
            currentCall = call;
            
            incommingCallToast.show();
            document.getElementById('callerUsername').innerText = call.metadata.callerUsername;

            document.getElementById('acceptCallButton').onclick = function() {
                incommingCallToast.hide();
                call.answer(localStream);  // Use apenas localStream aqui
                call.on('stream', function(remoteStream) {
                    remoteAudioElement = new Audio();
                    remoteAudioElement.srcObject = remoteStream;
                    remoteAudioElement.play();
                    document.getElementById('endCallButton').style.display = 'flex';
                });

                call.on('close', function() {
                    incommingCallToast.hide();
                    showErrorToast('Chamada encerrada.');
                    document.getElementById('endCallButton').style.display = 'none';
                });
            };

            document.getElementById('rejectCallButton').onclick = function() {
                incommingCallToast.hide();
                call.close();
            };
        });

        // Realizar a chamada ao clicar no botão
        document.getElementById('audioCallButton').addEventListener('click', function() {
            $.ajax({
                url: `/friends/${currentFriendId}`,
                method: 'GET',
                success: function (data) {
                    if (data.friend) {
                        const friend = data.friend;

                        if(!friend.online)
                            return showErrorToast("O seu amigo está offline, portanto não pode receber chamadas.");

                        document.getElementById('calleeUsername').innerText = friend.username;
                        callingToast.show();

                        console.log('Calling peer ID: ' + friend.peerid);

                        var call = peer.call(friend.peerid, localStream, {
                            metadata: { callerUsername: currentUsername }
                        });

                        currentCall = call;

                        call.on('stream', function(remoteStream) {
                            remoteAudioElement = new Audio();
                            remoteAudioElement.srcObject = remoteStream;
                            remoteAudioElement.play();
                            document.getElementById('endCallButton').style.display = 'flex';
                            callingToast.hide();
                        });

                        document.getElementById('rejectCallButton').onclick = function() {
                            callingToast.hide();
                            call.close();
                        };

                        call.on('close', function() {
                            callingToast.hide();
                            showErrorToast('Chamada encerrada.');
                            document.getElementById('endCallButton').style.display = 'none';
                        });

                    } else {
                        showErrorToast('Dados do amigo não encontrado.');
                    }
                },
                error: function (jqXHR) {
                    const errorMessage = jqXHR.responseJSON ? jqXHR.responseJSON.error : 'Dados do amigo não encontrados.';
                    showErrorToast(errorMessage);
                }
            });
        });

        document.getElementById('endCallButton').onclick = function() {
            callingToast.hide();

            if (currentCall) {
                currentCall.close();
                currentCall = null;
                document.getElementById('endCallButton').style.display = 'none';
                showErrorToast('Chamada encerrada.');
            } else {
                document.getElementById('endCallButton').style.display = 'none';
                showErrorToast('Nenhuma chamada ativa para encerrar.');
            }
        };

        // Controlar volume e mute
        var muteButton = document.getElementById('muteButton');
        var isMuted = false;

        muteButton.addEventListener('click', function() {
            const icon = muteButton.querySelector('i');
            if (remoteAudioElement) {
                isMuted = !isMuted;
                remoteAudioElement.muted = isMuted;

                if (isMuted) {
                    icon.classList.remove('fa-microphone');
                    icon.classList.add('fa-microphone-slash');
                    icon.style.color = '#FF6347'; // Define a cor para '#FF6347' quando o microfone está mutado
                } else {
                    icon.classList.remove('fa-microphone-slash');
                    icon.classList.add('fa-microphone');
                    icon.style.color = 'white'; // Define a cor para 'white' quando o microfone está desmutado
                }
            }
        });
    }).catch(function(err) {
        showErrorToast('Failed to get local stream', err);
    });
} else {
    showErrorToast('Seu navegador não suporta a API getUserMedia.');
}

By the way, the user can establish a connection, I can hear and be heard, I can end the call, etc., the only problem is the mute/unmute, besides, am I using good practices in this code?

How could I close this navbar by clicking out of it?

`import './SideNavBar.scss';
import { useState } from 'react';
import { Cancel01Icon, Menu01Icon } from '../assets/icons';
import { Link } from 'react-router-dom';

const SideNavBar = () => {

const [isOpen, setIsOpen] = useState(false);

const toggleMenu = () => setIsOpen(!isOpen);

   return (
  <>
    <button className="menu-button" onClick={toggleMenu}>

     {isOpen ? <Cancel01Icon className='sideicon' /> : <Menu01Icon className='sideicon' />}

    </button>

  <nav className={`side-navbar ${isOpen ? 'open' : ''}`}>
    <ul className='side-navbar-ul'>
      <li className='side-navbar-li'><Link to={'/'}>Home</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><Link to={'/loja'}>Loja</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><Link to={'/galeria'}>Galeria</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><Link to={'/contato'}>Contato</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><a>Restrito</a></li>
        <div className='line'></div>
        
      

         </ul>
       </nav>
     </>

     )};

     export default SideNavBar;`

#How could I make this navbar close when I click in out of it, considering that this is a React app? I’ve seen somethings but it’s more like vanila js, I need to know how to do this in a React component, jsx

GraphJS mouse hover timezone

I’m working on building a status page for all of my microservices using graphjs (page available here), and when hovering over points of data the timezone is UTC, but I was hoping there’s a way to set it automatically based on the user’s timezone.

My config for the graphs is

          <script>
              new Chart(document.getElementById('chart-${index}'), {
                  type: 'line',
                  data: {
                      labels: ${JSON.stringify(labels)},
                      datasets: [{
                          label: 'Response Time',
                          data: ${JSON.stringify(datapoints)},
                          fill: true,
                          borderColor: '#43b581',
                          cubicInterpolationMode: 'monotone',
                          tension: 0.2,
                          pointBorderWidth: 0
                      }]
                  },
                  options: {
                      responsive: true,
                      maintainAspectRatio: false,
                      scales: {
                          x: {
                              display: false
                          },
                          y: {
                              beginAtZero: true
                          }
                      },
                      plugins: {
                          legend: {
                              display: false
                          }
                      }
                  }
              });
          </script>

InvalidKeySpecException In Java

I have a client (an Android app with Java) and a Node.js server. I want to generate a shared secret using the client’s and server’s Diffie-Hellman public keys.

The server and the client send their Diffie-Hellman public keys to each other over TCP (Transmission Control Protocol) so that they may generate a shared secret. When the server sends its public key to the client as a base64 string, I can successfully convert this string to bytes on the client-side.

The problem is that, when converting the bytes to a PublicKey instance on the marked Line 8, I get the error:

java.security.spec.InvalidKeySpecException: encoded key spec not recognized: failed to construct sequence from byte[]: DER length more than 4 bytes: 33

Here’s my Java code:

public boolean generateSharedSecret() throws Exception {
        byte[] serverDiffieHellmanPublicKey = receiveDiffieHellmanPublicKey();

        Log.e("String Length", String.valueOf(Base64.encodeToString(serverDiffieHellmanPublicKey, Base64.DEFAULT).length())); // Outputs 90.
        Log.e("Bytes Length", String.valueOf(serverDiffieHellmanPublicKey.length)); // Outputs 64.

        KeyFactory keyFactory = KeyFactory.getInstance("DH");
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(serverDiffieHellmanPublicKey); // Line 8
        PublicKey dhPublicKeyFromServer = keyFactory.generatePublic(x509EncodedKeySpec);

        // ...
}

public byte[] receiveDiffieHellmanPublicKey() {
    try {
        Socket socket = new Socket("185.255.95.248", 1211);
        InputStream inputStream = socket.getInputStream();

        byte[] buffer = new byte[1024];
        int bytesRead = inputStream.read(buffer);
        String keyString = new String(buffer, 0, bytesRead);
        return Base64.decode(keyString, Base64.DEFAULT);
    } catch (Exception ignore) {}

}

Here’s my Node.js code:

const net = require("net");
const crypto = require("crypto");
const dh = crypto.createDiffieHellman(512);
const serverDiffieHellman = crypto.generateDiffieHellman(dh.getPrime());

net.createServer((socket) => {
    socket.on("connect", () => socket.write(serverDiffieHellman.getPublicKey().toString("base64")));
}).listen(1211, "185.255.95.248", () => console.log("TCP server is running..."));

Any help will be pleasantly appreciated. Thanks, regards…

Firebase permission denied even when authenticated

I have a basic database with these rules

{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

I try reading from the database path /users/+storageuid

const storageuid = localStorage.getItem("uid");
export const testCall = ()=>{
    
    const dbRef = ref(getDatabase());
    const path = "/users/"+storageuid;
    
    get(child(dbRef, path)).then((snaphot) => {
        if (snapshot.exists()) {
            console.log(snapshot);
        } else {

        }
    }).catch((error) => {
        console.log(error);
    });
}

Where storageuid is my authentication uid after google signin. I place it in localstorage.setItem(“uid”);
And I still get a permission denied..

EXIF.getData() function always returns an empty string and “undefined”

I’m developing a simple Chromium extension that reads EXIF data and shows to the user but in the library I’m using (which is Exif.js), I feel like there are things I’m not doing correctly because the output is always an empty string and undefined. Here’s the code:

const img = document.getElementById("someImage");

window.onload = getExif(img);

function getExif(file) {
    try {
        EXIF.getData(file, function () {
            if (file) {
                var make = EXIF.getTag(this, "Make");
                var model = EXIF.getTag(this, "Model");
                var allMetaData = EXIF.pretty(this);

                console.log(JSON.stringify(allMetaData, null, 2));
                console.log(make, model);
            } else {
                console.error("EXIF data has not been found or incomplete.");
            }
        });
    } catch (error) {
        console.error("Error reading EXIF data", error);
    }
}

“make” and “model” always returns an “undefined” from an image I’m using through classical const img = document.getElementById(someImage) in popup.html as well as allMetaData returning and empty string.

I’ve followed the “Usage” section in the documentation but nothing appears to be fixing this.

How to disable the automatic scroll of browser on back navigation

I have a Product Listing Page and Product Detail Page. The products in PLP are listed dynamically through graphql. The scenario is when a product is clicked on the PLP it takes me to PDP and when browser’s back button is clicked, it takes me back to PLP. Now, as we know browsers have default scroll set for back navigation to that part of the page till where it was last scrolled to. So, same is happening here, when I click on back button from PDP and it lands on PLP,the page is landed on the part where it was last scrolled to but in some cases where internet is slow and there is no html as data is dynamic, it slides to the bottom, i.e., footer and then it has to be manually scrolled to the product DOM. I tried to disable the automatic scroll for the PDP click scenario using the below code:

if ('scrollRestoration' in history) {
    history.scrollRestoration = 'auto';
}

This works if I run this directly without any condition. But for my case, I have added the Product Id of the product which is clicked on the page in Session Storage. So, I need to check that variable if it exists in session storage, if yes then only the above code will run. So, the getting of session storage takes time and browser already initiates the auto scroll. Below is the code:

if(!sessionStorage.getItem("productId")){
  if ('scrollRestoration' in history) {
      history.scrollRestoration = 'auto';
  }
}

Is there any way I can run this code first when the page is loading. I have tried document ready but also not working. Anything which can work just when page is landed, even before html is rendered?

Local storage doesn’t work on reload. Why?

I have a list of items that should be saved if they are open also an ‘active’ item that is currently previewed. Everything disappears on reload.


const Projects = () => {
    const [allProjectsOpen, setAllProjectsOpen] = useState(false);
    const [reactProjectsOpen, setReactProjectsOpen] = useState(false);
    const [angularProjectsOpen, setAngularProjectsOpen] = useState(false);
    const [openItems, setOpenItems] = useState([]);
    const [activeItem, setActiveItem] = useState(null);


    const projectItemsRef = useRef([
        {
            name: '_photo_portfolio',
            icon: <RiJavascriptFill className="w-6 h-6 text-custom-blue" />,
            type: 'react',
            component: PhotoPortfolio,
        },
        {
            name: '_angul_it',
            icon: <FaAngular className="w-6 h-6 text-custom-purple" />,
            type: 'angular',
            component: AngulIt,
        },
        {
            name: '_unknown_project',
            icon: <RiJavascriptFill className="w-6 h-6 text-custom-blue" />,
            type: 'react',
            component: UnknownProject,
        },
    ]);



    // Load state from localStorage
    useEffect(() => {
        const storedOpenItemNames = JSON.parse(localStorage.getItem('openItemNames')) || [];
        const storedActiveItemName = localStorage.getItem('activeItemName');

        const storedOpenItems = projectItemsRef.current.filter(item => storedOpenItemNames.includes(item.name));
        setOpenItems(storedOpenItems);
        setActiveItem(storedActiveItemName || null);
    }, []);


    // Save state to localStorage
    useEffect(() => {
        // Save state to localStorage when openItems or activeItem changes
        const openItemNames = openItems.map(item => item.name);
        localStorage.setItem('openItemNames', JSON.stringify(openItemNames));
        localStorage.setItem('activeItemName', activeItem);
    }, [openItems, activeItem]);



    // Add item to openItems
    const addItem = (item) => {
        setOpenItems((prevItems) => {
            // Prevent adding duplicates
            if (prevItems.some(prevItem => prevItem.name === item.name)) {
                return prevItems;
            }
            return [...prevItems, item]; // Add item to the openItems array
        });
        setActiveItem(item.name); // Set the newly added item as active
    };


    // Remove item from openItems
    const removeItem = (itemName) => {
        setOpenItems((prevItems) => prevItems.filter((prevItem) => prevItem.name !== itemName));
        if (activeItem === itemName) {
            setActiveItem(null); // Reset active item if it's removed
        }
    };

    return (
        <div>
            <div>
                <ItemList
                    items={openItems}
                    activeItem={activeItem}
                    setActiveItem={setActiveItem}
                    removeItem={removeItem} />
                <div>
                    {ActiveComponent && <ActiveComponent />}
                </div>
            </div>
        </div>
    );
};


I’m trying to save this to local storage so on reload it would have the list and the active item open. I can see it saves the items and active item to local storage but on reload everything disappears.