How can I unsubscribe from Firebase onSnapShot in an RTK Query?

I’m creating an app in React Native that depends on realtime updates. When a user updates the data in their session, another user needs to immediately see that update without refreshing their app. I’m using RTK Query to manage my store, but can’t figure out how to close the memory leak if I use onSnapShot in my query. Is there another Redux solution I need to consider?

I’ve tried passing the data through props to manage the data but the management becomes a little complicated when using complex components.

Pass React State Down As Prop, Without Defined Children Components

We’re working on an admin portal. We’ve got a user account page, where the user will be able to edit their personal info and eventually stuff like security, privacy, notifications, etc.

Note: We’re using classes and not functions. Let’s skip the questions on “why” or trying to “sell me this pen” on using functions over classes.

Note: Also, for reference, we’re using https://mui.com. Just in case you need to know.

  1. We’ve got a page template for all portal pages, called <PortalTemplate/>.
  2. On the PortalTemplate, we are using a cookie, to execute a getUser() function that returns user details. This is captured in this.state.account.
  3. The user’s account page is injected as this.props.children.
// PORTAL TEMPLATE (basic):
export interface PageProps {
  children: any;
  pageTitle: string;
}

export interface PageState {
  account: AccountDTO;
  anchorEl: HTMLElement | null;
  isLoginActive: boolean;
  isMenuOpen: boolean;
}

export default class PortalTemplate extends React.Component<PageProps, PageState> {
  render() {
    return(
      <div>
        {this.props.children}
      </div>
    );
  }
}

This portal template is used for ALL portal pages, as sort of like a wrapper that contains the global menu stuff. We’re trying to determine how to actually leverage the state variables, but also sending this down to children component pages so they can use the same details to render dynamic data.

// ACCOUNT PAGE (basic):
export default class AccountPage extends React.Component<PageProps> {
  constructor(props: PageProps) {
    super(props);
  }

  render() {
    return (
      <PortalTemplate pageTitle='Account'>
      { page content here }
      </PortalTemplate>
  )};
}

Our problem is that we’re having trouble sending the this.state.account data down from PortalTemplate to AccountPage so that the user’s account page can use these details to render the data, but also have a form where they can edit their details.

React Ref:
https://beta.reactjs.org/learn/sharing-state-between-components#step-3-add-state-to-the-common-parent

We tried using this reference, but are finding it hard to follow. Since our PageTemplate component uses { this.props.children } to allow components to be used “under” it, we’re not able to figure out where this.state.account is supposed to go in order to be utilized by child pages/components.

We’ve also tried to clone the child, like other posts have depicted, but was unsuccessful.

{React.cloneElement(this.props.children)}

cant click the button (electron)

im try to do a project that connect pc to pc like screencast. when following the coding online im having a problem when trying to click the button. i cant click the button to pup up the id code.

This the code for app.js


const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const { v4: uuid4} = require('uuid');
const screenshot= require('screenshot-desktop');

var socket = require('socket.io-client')('http://172.20.10.3:5000');
var interval;


const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 500,
    height: 150,
    webPreferences: {
      preload: path.join(__dirname, 'index.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.removeMenu();
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0)
    createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin')
  app.quit()
})

ipcMain.on("start-share", function(event , arg){

    var uuid = uuid4();
    socket.emit("join-message", uuid);
    event.reply("uuid", uuid);

})
ipcMain.on("stop-share", function(event, arg){


})


// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

This is the index.js file

const ipcRenderer = require ('electron').ipcRenderer;

window.onload = function(){

    ipcRenderer.on("uuid", (event, data)=>{
        document.getElementById("code").innerHTML = data;
    })

}

function startShare(){
    ipcRenderer.send("start-share", {} );
    document.getElementById("start").style.display = "none";
    document.getElementById("stop").style.display = "block";

}

function stopShare(){
    ipcRenderer.send("stop-share", {});
    document.getElementById("stop").style.display = "none";
    document.getElementById("start").style.display = "block";
}

this is the popup when running the code. i cant click the start button
enter image description here

im following this video from (youtube)
this the documentation that i follow in electronelectron website

if someone having problem to see the codes i will try to edit and insert more code or maybe send a zip file. im really needed some help in developed this project for education purpose

im expecting some guide to develop this project. if can i would like the same in the video but i have follow that video from start to end but stuck in the middle of the video. really needed the help

How to change state in a React component?

I’m trying to get into details with React and make a simple Quiz app. I get some locally saved data and render it on the page. However, when I try to change state with data from true to false (toggle function), I get an error. Once it’s triggered I get the following error: Cannot read properties of undefined (reading ‘map’). Could you please let me know where the bug is? Thanks in advance.

  const questBlocks = data.map((elem, index) => {
    const ansBlocks = elem.answers.map((ans) => (
      <Answer
        toggle={toggle}
        isSelected={ans.selected}
        ans={ans.text}
        key={ans.id}
        id={ans.id}
      />
    ));
    return (
      <div key={index}>
        <Question question={elem.question} />
        <div className="answerCont">{ansBlocks}</div>
      </div>
    );
  });

  function toggle(id) {
    setData((prevData) => {
      return prevData.map((question) => {
        return question.answers.map((answer) => {
          return answer.id === id
            ? { ...answer, selected: !answer.selected }
            : answer;
        });
      });
    });
  }```

FormSubmit shows pages ” The form was submitted successfully. And nothing is sending

FormSubmit.co shows the page ” The form was submitted successfully. Return to original site:” And it doesn’t redirect to my strong end and doesn’t send a message to my email address, I will add that sometimes it works correctly and sometimes it doesn’t, I don’t know what it depends on or someone can help me ? I will add that I created my code without any skills, please have mercy


<script>
    $(document).ready(function () {
    $('#submit').click(function() {
      check = $('option[disabled]:selected').length;
      if(check == 8) {
        document.getElementById("pole1").innerHTML="<b>WYBIERZ SMAK I ILOŚĆ KTÓRA CIĘ INTERESUJE !!!!</b>";
        document.getElementById("pole1").style.color="red";
        document.getElementById("pole1").style.fontSize ="30px";
        return false;
      }

    });
});
    $(document).ready(function () {
    $('#input1').keyup(function(){
      var input1 = $('#input1').val();
      var input3 = $('#input3').val();
      $('#input2').val('NEW ORDER ' + input1 + ', PACZKOMAT : ' + input3 );
});
$('#input3').keyup(function(){
      var input1 = $('#input1').val();
      var input3 = $('#input3').val();
      $('#input2').val('NEW ORDER ' + input1 + ', PACZKOMAT : ' + input3 );
});
});
</script>

</head>

<div id="form"></div>

       
      

       <form 
    action=here is my email to which new submissions are coming in in the form of a special link  " method="POST" id="myform">

    <input type="hidden" id="input2" name="_subject" value="">

    <input type="hidden" name="_next" value=here is a redirect to the next page that should appear after completing the entire form ">

    <input type="hidden" name="_template" value="table">

        
// here should be 8 different select options 
           

            <div class="numer"><center>
                <label for="phone"><b>Twój numer telefonu</b></label> <br>
                <input type="tel" id="phone" name="Numer telefonu" placeholder="Wpisz swój numer telefonu" size="27" style="margin-top: 5px;" maxlength="12" required><br><br>
            </center></div>
                
           <div class="adres"><center>
                <label><b>Dokładny adres paczkomatu</b></label> <br>
                <div class="map11"><input type="text" name="Adres Paczkomatu" placeholder="Wpisz  dokładny adres swojego paczkomatu" size="43" required>
                <a href="URL" target="_blank"><img class="image1" src="URL" width="25px" height="25px"></a> 
                <a href="URL" target="_blank"><img class="image2" src="URL" width="25px" height="25px"></a>
            </center></div><br><br>

            <div class="numer.paczkomatu"><center>
                <label><b>Numer wybranego paczkomatu</b></label> <br>
                <div class="map22"><input class="map22" type="text" id="input3" name="Numer paczkomatu" placeholder="Wpisz numer wybranego paczkomatu" size="35" maxlength="8" required>
                <a href="URLt" target="_blank"><img class=" image11" src="URL" width="25px" height="25px"></a> 
                <a href="URL" target="_blank"><img class=" image22" src="URL" width="25px" height="25px"></a>
            </center></div> <br>
        </div>
            

           <center><input value="Wyślij" type="submit" id="submit"></button></center>
        
    </form>
</body>
</html>

in the following code “location.replace(“./mc.html”)” only takes effect after i reload the page how do i fix this?

in the following code “location.replace(“./mc.html”)” only takes effect after i reload the page how do i fix this?

/* CSS for the main page */ #main-page { display: none; } /* CSS for the passcode input form */ #passcode-form { display: none; } /* CSS for the 404 page */ #404-page { display: none; } Enter passcode: Submit 404 @import url(‘https://fonts.googleapis.com/css?family=Fira+Mono:400’); body{ display: flex; width: 100vw; height: 100vh; align-items: center; justify-content: center; margin: 0; background: #131313; color: #fff; font-size: 96px; font-family: ‘Fira Mono’, monospace; letter-spacing: -7px; } div{ animation: glitch 1s linear infinite; } @keyframes glitch{ 2%,64%{ transform: translate(2px,0) skew(0deg); } 4%,60%{ transform: translate(-2px,0) skew(0deg); } 62%{ transform: translate(0,0) skew(5deg); } } div:before, div:after{ content: attr(title); position: absolute; left: 0; } div:before{ animation: glitchTop 1s linear infinite; clip-path: polygon(0 0, 100% 0, 100% 33%, 0 33%); -webkit-clip-path: polygon(0 0, 100% 0, 100% 33%, 0 33%); } @keyframes glitchTop{ 2%,64%{ transform: translate(2px,-2px); } 4%,60%{ transform: translate(-2px,2px); } 62%{ transform: translate(13px,-1px) skew(-13deg); } } div:after{ animation: glitchBotom 1.5s linear infinite; clip-path: polygon(0 67%, 100% 67%, 100% 100%, 0 100%); -webkit-clip-path: polygon(0 67%, 100% 67%, 100% 100%, 0 100%); } @keyframes glitchBotom{ 2%,64%{ transform: translate(-2px,0); } 4%,60%{ transform: translate(-2px,0); } 62%{ transform: translate(-22px,5px) skew(21deg); } } // Get the current URL var currentUrl = window.location.href; // Check if the current URL contains “?the_passcode” if (currentUrl.indexOf(“?the_passcode”) !== -1) { // Check if the passcode is stored in local storage var passcode = localStorage.getItem(“passcode”); if (passcode === “711iscool”) { // Show the main page document.getElementById(“main-page”).style.display = “block”; document.getElementById(“passcode-form”).style.display = “none”; location.replace(“./mc.html”) } else { // Show the passcode input form document.getElementById(“passcode-form”).style.display = “block”; document.getElementById(“404-page”).style.display = “none”; // Add an event listener to the submit button document.getElementById(“submit-passcode”).addEventListener(“click”, function() { // Get the value of the passcode input var inputPasscode = document.getElementById(“passcode-input”).value; // Check if the input passcode is equal to “711iscool” if (inputPasscode === “711iscool”) { // Store the passcode in local storage localStorage.setItem(“passcode”, inputPasscode); // Show the main page document.getElementById(“main-page”).style.display = “block”; document.getElementById(“passcode-form”).style.display = “none”; } else { // Show an error message alert(“Incorrect passcode. Please try again.”); } }); } } else { document.getElementById(“404-page”).style.display = “block”; setTimeout(function() { window.location.href = “https://www.youtube.com/@TechGeekUnited”; }, 10000); }

It to redirect to [the current url]/mc.html when the correct passcode is entered.

Sveltekit JS : How to import a library into svelte page?

I have tried importing my Kafka library inside page.svelte, and it has thrown an error saying it is not allowed to import Kafka inside the script.

<script>                                   
  import Table from "$lib/Table.svelte";   
  import {Kafka, logLevel} from 'kafkajs'; 

</script>    

Later I found we can export the kafka producer by setting the kafka import in hooks.server.js. I imported the kafka library in hooks.server.js and added the producer in event.locals. Later exported it to my script tag of page.svelte.

  export let producer; 

Still, the value of producer is undefined. Any leads on how to expose the imports from hooks.server.js to svelte.page could be much appreciated.

Passing Variable from Another Module’s Function

I’m new with JS/NodeJs.

I managed to authenticate with Google Firebase

verifyFirebase.js:

  function checkAuth(req, res, next) {
    if (req.header('auth-token')) {
      admin.auth().verifyIdToken(req.header('auth-token'))
        .then((decodedToken) => {
            //return uid
            let uid = decodedToken.uid
          next()
        }).catch((err) => {
            console.log(err);
          res.status(403).send('Unauthorized')
        });
    } else {
       
      res.status(403).send('Unauthorized')
    }
  }



module.exports.checkAuth = checkAuth;

and I’m using it on the another files as below;

routes.js

const verify_firebase = require('./verifyFirebase').checkAuth;


router.get('/', verify_firebase, (req,res) => {
    res.json("verified");
})

The “/” route is protected with verify_firebase function coming from verifyFirebase.js.
How can I access uid variable from routes.js? Because I need to access this uid within secured route.

Given an object that satisfies the TypeScript type: Record any>

const funcs = {
 repeat(val: string, times: number): string[] {
 const arr: string[] = [];
 for (let i = 0; i < times; ++i) {
 arr.push(val);
 }
 return arr;
 },
 wrap(value: number): { value: number } {
 return { value }
 }
}

Write a higher-order function, convertReturnedValuesToJSON that accepts a single
parameter that satisfies the type Record<string, (...args: any[]) => any>
and returns a new object where
a) all of the field names are changed by appending the string “JSON” to the end of the
field name
b) instead of the function’s return value, return JSON serialized value.
For instance, using the funcs object above:

const converted = convertReturnedValuesToJSON(funcs)

the type of converted should be:

 repeatJSON: (val: string, times: number) => string;
 wrapJSON: (value: number) => string;
}```

Convert/annotate the throttle function into its type-safe TypeScript equivalent

  1. The best outcome is that we enforce that the function which is returned by the
    throttle function has exactly the same signature as func, regardless of how many
    parameters func takes.
  2. Using incorrect types or the wrong number of parameters when
    calling the wrapped function should result in a compiler error.
function throttle(func: Function, timeout: any) {
 let ready = true;
 return (...args: any) => {
 if (!ready) {
 return;
 }
 ready = false;
 func(...args);
 setTimeout(() => {
 ready = true;
 }, timeout);
 };
}

function sayHello(name: string): void {
 console.log(`Hello ${name}`);
}

const throttledSayHello = throttle(sayHello, 1000);
// this should result in compilation failure
throttledSayHello(1337);
// so should this
const throttledSayHello2 = throttle(sayHello, "breakstuff");

How to wait for an event listener and read its returned value?

I am developing my first Firefox add-on, and in one of my event listeners, I need to communicate with a native app, wait for it to return, fetch its response, and proceed with the rest of the code.

Here is a simplified version of the code:

let port = browser.runtime.connectNative("my_native_app");
const request = new XMLHttpRequest();

request.addEventListener("load", () => {
    port.postMessage("status");
    // Wait for the port to communicate with the local app and fetch its returned value
});

port.onMessage.addListener((response) => {
    // Return response to be used in "load" event listener
});

I have two questions about how I can implement this:

  1. What is the best way to share the return value of the latter listener with the callee? I have read that using a global variable can help, but I do not know how to ensure I read the variable’s value after it is updated.

  2. How can I wait for the latter listener to return its value? I have found that an await line could help, but I am unsure how to write the latter listener to return a Promise that can be used in the await block.

how to use active class in vue js

i’m trying to change the text-color when a component is active

here’s my template

           <div
           v-if="enabled2FAs.includes('phoneOtp')"
              @click="otpType = 'phoneOtp'"
            >
              <div
                  :class="[isActive ? activeClass: 'red',]">
                Phone OTP
              </div>
            </div>

          <div
           v-if="enabled2FAs.includes('authenticatorApp')"
              @click="otpType = 'authenticatorApp'"
            >
              <div
                  :class="[isActive ? activeClass: 'red',]">
                Phone OTP
              </div>
            </div>

my sxript tag


<script>
export default {
  data() {
    return {
      isActive: true,
    };
  },
 
};
</script>

pleaase how can i go about this

TypeError: snapshot.forEach is not a function – Loop through firebase database

I am struggling to understand why my function is failing when trying to loop through a snapshot from Firebase Realtime Database.

The function should read through each ‘Topic’, from within each ‘Topic’ there is an ‘Articles’ field which has approximately 10 articles associated with it. The function reads each article URL and scrapes the URL for the largest image on the article website.
It should then add a new field ‘imageURL’ to each ‘Article’.

When deployed I receive the following:

TypeError: snapshot.forEach is not a function

scraper.js

exports.imageScraper = functions.database.ref("searchTrends/google")
.onUpdate((snapshot, context) => {
  functions.logger.error(snapshot);
  snapshot.forEach(function(trendSnapshot) {
    // TrendSnapshot - Key is topic Num
    // Value is topic details with list of articles
    const topicNum = trendSnapshot.key;
    trendSnapshot.forEach(function(innerChild) {
      if (innerChild.key == "articles") {
        innerChild.forEach(function(articleData) {
          const articleNum = articleData.key;
          const myUrl = articleData.child("url").val();
          // console.log(myUrl);

          const options = {
            url: myUrl,
          };
          // console.log(options);

          ogs(options, (error, results, response) => {
            if (typeof results.ogImage === "undefined") {
              console.log("no Image");
            } else {
              if (results.ogImage.url === undefined) {
                return "done";
              }
              console.log(articleNum);
              const DBRef = admin.database().ref("searchTrends/google/" +
              topicNum + "/articles/" + articleNum);
              DBRef.update({imageURL: results.ogImage.url});
            }
          });
        });
        return "done";
      }
    }).catch((error) => {
      console.log("Transaction failed: ", error);
      return null;
    });
  });
});

function doesn’t register variable change

I’m trying to make a small game with Javascript where the user has to enter the sum of two random numbers (a and b).When you click on a button or when you press enter, it calls a function which checks if the sum is the same as what you entered. If that’s the case, the function play() is called again and a and b change. It works fine the first time, but the second time, unless the second sum is equal to the first one, it doesn’t work. What does my answer() function acts as if a and b didn’t change ?

let count = 0;
function play(){


if (count < 10){
   // setTimeout(loss, 30000);
    count += 1;
    document.getElementById("user-answer").value = "";
    var a = Math.floor(Math.random() * 20) + 1;
    var b = Math.floor(Math.random() * 20) + 1;
    
    var question = document.getElementById("question");
    question.textContent = a + " + " + b;


    function answer(){
        var result = a + b;
        var userAnswer = document.getElementById("user-answer").value;
        
        if(userAnswer == result){
            sound.play();
            //clearTimeout();
            play();
        } 
        if(userAnswer != result) {
            document.getElementById("user-answer").classList.add("wrong");
          //  document.getElementById("user-answer").disabled = true;
            console.log(result);
            console.log(userAnswer);
          //  setTimeout(remove, 1000);
        }
    }

    window.addEventListener("keypress", function(event){
        if (event.key == "Enter"){
            answer();
        }
    })

    document.getElementById("send-answer").addEventListener("click", answer);

} else {
    document.getElementById("win").textContent = "You won!";
}

}

[Sequelize]M:N associations. Sequelize using its own column that do not exist

I’m trying to use a Many-to-Many relation here is my model :

const Refinement = sequelize.define('refinement', {
    ID          : { type: DataTypes.INTEGER(10), allowNull: false, autoIncrement: true, primaryKey: true },
    weaponID    : { type: DataTypes.INTEGER(10), allowNull: false },
    rank        : { type: DataTypes.TINYINT(1), allowNull: false },
},
{ freezeTableName: true, timestamps: false, })

const Refinement_Bonus = sequelize.define('refinement_effect', {
    ID          : { type: DataTypes.INTEGER(10), allowNull: false, autoIncrement: true, primaryKey: true },
    refinementID: { type: DataTypes.INTEGER(10), allowNull: false },
    effectID    : { type: DataTypes.INTEGER(10), allowNull: false },
},
{ freezeTableName: true, timestamps: false, })

const EffectBonus = sequelize.define('effectbonus', {
    ID          : { type: DataTypes.INTEGER(10), allowNull: false, autoIncrement: true, primaryKey: true },
    refinementID: { type: DataTypes.INTEGER(10), allowNull: false },
    isPercentage: { type: DataTypes.BOOLEAN, allowNull: false },
    targetStat  : { type: DataTypes.CHAR(16), allowNull: false },
    sourceStat  : { type: DataTypes.CHAR(16), allowNull: false },
    sourceRatio : { type: DataTypes.FLOAT(4,3), allowNull: false },
    isOptionnal : { type: DataTypes.BOOLEAN, allowNull: false },
    isStackable : { type: DataTypes.BOOLEAN, allowNull: false },
},
{ freezeTableName: true, timestamps: false, })

Refinement.belongsToMany(EffectBonus, {through: Refinement_Bonus, targetKey:"refinementID"});
EffectBonus.belongsToMany(Refinement, {through: Refinement_Bonus, foreignKey:"effectID"});

And I’m getting this error sqlMessage: "Unknown column 'effectbonus.effectbonuID' in 'field list'"

    sqlMessage: "Unknown column 'effectbonus.effectbonuID' in 'field list'",
    sql: 'SELECT `refinement`.*, `effectbonus`.`ID` AS `effectbonus.ID`, `effectbonus`.`refinementID` AS `effectbonus.refinementID`, `effectbonus`.`isPercentage` AS `effectbonus.isPercentage`, `effectbonus`.`targetStat` AS `effectbonus.targetStat`, `effectbonus`.`sourceStat` AS `effectbonus.sourceStat`, `effectbonus`.`sourceRatio` AS `effectbonus.sourceRatio`, `effectbonus`.`isOptionnal` AS `effectbonus.isOptionnal`, `effectbonus`.`isStackable` AS `effectbonus.isStackable`, `effectbonus`.`effectbonuID` 
AS `effectbonus.effectbonuID`, `effectbonus->refinement_effect`.`ID` AS `effectbonus.refinement_effect.ID`, `effectbonus->refinement_effect`.`refinementID` AS `effectbonus.refinement_effect.refinementID`, `effectbonus->refinement_effect`.`effectID` AS `effectbonus.refinement_effect.effectID` FROM (SELECT `refinement`.`ID`, `refinement`.`weaponID`, `refinement`.`rank` FROM `refinement` AS `refinement` LIMIT 1) AS `refinement` LEFT OUTER JOIN ( `refinement_effect` AS `effectbonus->refinement_effect` INNER JOIN `effectbonus` AS `effectbonus` ON `effectbonus`.`refinementID` = `effectbonus->refinement_effect`.`effectID`) ON `refinement`.`ID` = `effectbonus->refinement_effect`.`refinementID`;',

I REALLY don’t understand why sequelize keep using this column taken from I don’t even know where. Can someone explains me how it works please ? I’m starting to get tired of Sequelize…

Optionnal question: Can we also avoid all these renames ?