React mobx async state change issue

I’m using mobx stores in my react app for state management, I want to show an error modal for 5 seconds and then hide it, I use async in my mobx function but even though I set error variable to ”, the modal keeps showing, so error variable is correctly set to error message but it’s not coming back to default state “”, this means delay action is not correctly being awaited?

In AppStore.js

async handleAppError(error)
    {
        const delay = (ms) => new Promise((res) => setTimeout(res, ms));
        this.setError('¡Oops, algo salió mal! Intentalo más tarde');
        await delay(5000);
        this.setError('');
    }

setError(payload)
    {
        this.error = payload;
    }

How I show and hide modal is very simple, modal never actually hides after 5 seconds…

{ root.mapStore.error != '' && (
        <ErrorModal1></ErrorModal1>
        )}

How to get multiple key values from array in local storage?

I have a sign up form that asks for 6 details to create a user object, but I only need 2 of those details for a user to log in (username and password). I couldn’t figure out how to only get those 2 values from an object (comprised of 6 values) in the local storage, so I’ve made a separate array that holds those 2 required values (userLogin) and only added that to the local storage.

In the log in form, I’m trying to get it to see if my username and password input matches what has been stored, however I’m getting “ne” in the console, indicating that its not recognising a match. I’ve tried numerous ways of doing it and wording it, but I can’t seem to get it to work. I think the problem is that I’m not actually getting the items that I need, but I’m not entirely sure. Please have a look.

// Sign up page

const login = document.querySelector(".login");
const loginSubmit = document.querySelector(".loginSubmit");

let users = [];
let user = {};
let userLogin = [];

signupForm.addEventListener("submit", (e) =>{
    
    e.preventDefault();
    
    user = Object.fromEntries( [...document.querySelectorAll(".signup ul input")].map(e =>[e.name, e.value])); 

    users.push(user);
    userLogin.push(user.username);
    userLogin.push(user.password);

    localStorage.setItem('UserData', JSON.stringify(userLogin));
    console.log(localStorage);
});

// Log in page

const loginForm = document.querySelector(".login-form");

loginForm.addEventListener("submit", (e) => {
    let usernameInput = document.querySelector(".lg-username").value;
    let passwordInput = document.querySelector(".lg-password").value;
    e.preventDefault();
    if (localStorage.getItem("UserData")) {
        const dataUsername = JSON.parse(localStorage.getItem('UserData', 'username'));
        const dataPassword = JSON.parse(localStorage.getItem('UserData', 'password'));
        if(usernameInput === dataUsername && passwordInput === dataPassword) {
            console.log("ye");
        }else{
            console.log("ne");
        }
    }else{
        console.log("not regis");
    }

    console.log(localStorage)
});

sliding effect is not working in java script

I am making a Disney+ clone. In javascript code image sliding is not working. I have done my code in codesandbox.I tried to use carousel effect.But not working in my code.Images are showing,but sliding effect is not working.Please help me to solve this problem.
code is given below:

const carousel = document.querySelector(".carousel");
let arrays = [];
let slideIndex = 0; //to track the current slide
const createSlide = () => {
  if (slideIndex >= movies.length) {
    slideIndex = 0;
  }

  //create DOM elements
  let slide = document.createElement("div");
  var imgElement = document.createElement("img");
  let content = document.createElement("div");
  let h1 = document.createElement("h1");
  let p = document.createElement("p");

  //Attaching all the elements
  imgElement.appendChild(document.createTextNode(movies[slideIndex].image));
  h1.appendChild(document.createTextNode(movies[slideIndex].name));
  p.appendChild(document.createTextNode(movies[slideIndex].des));
  content.appendChild(h1);
  slide.appendChild(content);
  content.appendChild(p);

  slide.appendChild(imgElement);
  carousel.appendChild(slide);

  //setting up images
  imgElement.src = movies[slideIndex].image;
  slideIndex++;

  //setting elements classname
  slide.className = "slider";
  content.className = "slide-content";
  h1.className = "movie-title";
  p.className = "movie-des";

  arrays.push(slide);

  if (arrays.length) {
    arrays[0].styles.marginleft = `calc(-${100 * (arrays.length - 2)}%- ${
      30 * (arrays.length - 2)
    }px)`;
  }
};

for (let i = 0; i < 3; i++) {
  createSlide();
}

setInterval(() => {
  createSlide();
}, 3000);`

How to enter value when radio input is selected?

I have a line of code for custom radio input like this.
When selecting a radio the function will enter a random phone number into the hyperlink button, this works fine.

But how do you make a phone number somewhat non-randomized? so that I want to make in order of choice: for example when selecting “Select 30d” then the number used is “12345”, when selecting “Select 6m” then the number used is “23456”, when selecting “Select 1y” then the number used is ” used “34567”.

//Text result on custom selected package
  let result = document.querySelector('#result');
  document.body.addEventListener('change', function (e) {
    let target = e.target;
    let message;
    switch (target.id) {
      case '30day':
        message = 'Custom text shown on 30d selected.';
        break;
      case '6month':
        message = 'Custom text shown on 6m selected.';
        break;
      case '1year':
        message = 'Custom text shown on 1y selected.';
        break;
                     }
    result.textContent = message;
  });

  // Random WhatsApp number selected package
  const getRandomPhoneNumber = () => {
    const phoneNumbers = ["12345", "23456", "34567"]
    const randomIndex = Math.floor(Math.random() * (phoneNumbers.length))
    return phoneNumbers[randomIndex]
  }

  const link = document.querySelector('#link');
  const warning = document.querySelector('#warning');
  const url = "https://api.whatsapp.com/send";
  let changed = false;
  document.getElementById('select').addEventListener('change', function (e) {
    changed = true;
    warning.innerText = '';
    let target = e.target;
    const label = document.querySelector(`[for='${target.id}']`)
    let newUrl = url;
    newUrl += `?phone=${getRandomPhoneNumber()}`
    link.href = newUrl
  });

  link.addEventListener('click', () => {
    if (!changed) {
      warning.innerText = 'Custom text shown if package not selected'
      return;
    }
  });
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<!--custom selected package-->
  <div class="select-package" id="select" tabindex="1" style="margin:20px;">
    <input class="selectopt" name="package" type="radio" id="" checked>
    <label for="" class="option-package">Select package </label>
<br>
    <input class="selectopt" name="package" type="radio" id="30day">
    <label for="30day" class="option-package">Select 30d</label>
<br>
    <input class="selectopt" name="package" type="radio" id="6month">
    <label for="6month" class="option-package">Select 6m</label>
<br>
    <input class="selectopt" name="package" type="radio" id="1year">
    <label for="1year" class="option-package">Select 1y</label>
  </div>
  
  <!--Text result on selected package-->
  <p id="result" class="text-red text-small" style="margin:20px;"></p>
  <p id="warning" class="text-red text-small" style="margin:20px;"></p>
  <!--submit link-->
  <a id="link" class="btn btn-lg btn-danger" style="margin:20px;">Submit Link</a>

Chrome Extension: Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist

I am trying to pass data from background.js to popup.js, in background file it is giving the error:

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

Code is given below:

background.js

var currentUrl = '';

chrome.tabs.query(
    {
     lastFocusedWindow: true,
     active: true
    },
    function (tabs)
    {
        console.log('Active Tab')
        currentUrl = tabs[0].url        
        chrome.runtime.sendMessage({
            msg: "From Background"
         })
        
    });

popup.js

document.addEventListener("DOMContentLoaded", function() {
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
        console.log("From popup.js")
        console.log(request.msg)
     })
}); 

Manifest

 "manifest_version": 3,
    // "icons": {
    //     "16": "/images/icon-16x16.png",
    //     "32": "/images/icon-32x32.png",
    //     "48": "/images/icon-48x48.png",
    //     "128": "/images/icon-128x128.png"
    // },
    "background": {
        "service_worker": "background.js"
    },
    "action": {
        "default_popup": "index.html",
        "default_title": "Agile SEO Super Cluster",
        "default_icon": {
            "16": "16x16.png",
            "32": "32x32.png"
        }
    },
    "permissions": [
        "storage",
        "activeTab",
        "scripting",
        "tabs"
    ],
    "host_permissions": [
        "https://www.google.com/*"
    ]
}

how to fix Nan javascript

when I start to write in the htPrice field, Nan appears in the ttcPrice field, how can i fix this?

calculatTTC() {
     const htPrice = parseFloat(this.htpriceTargets[0].value);
     const tvaPercent = parseFloat(this.tvaTargets[0].value);
     const ttcPrice= parseFloat(preTaxPrice + vatPercent);
    if (isNaN(htPrice) && isNaN(tvaPercent)) {
        this.ttcPriceTargets[0].value = 'the value is not correct';
    } else {
        this.ttcPriceTargets[0].value = ttcPrice;
    }

}

Cleanup a function with parameters inside a loop of event listener (reactjs)

I don’t really know what is going on, but I think that the removeEventListener is not working properly.
Here is my code, my app is crashing everytime I click more than 5 times on any of the buttons and I can’t find a solution anywhere.

const doTri = (e) => {
    if(e.id === "active"){
      setOrder(!order);
    }
    else {
      document.getElementById("active")?.removeAttribute("id");
      e.setAttribute('id', 'active');
      setTri(e.classList[1]);
      setOrder(true)
    }
  }

useEffect(() => {
    Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
      e.addEventListener('click', ()=>{doTri(e)})
    })
  
    return () => {
      Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
        e.removeEventListener('click',()=>{doTri(e)})
      })
    }
  }, [tri,order])

How can I sum the sum of a property of an javascript array in an array of objects?

I’m making a game where each player can submit an answer on a given question and other players can vote on an answer of another player. I store these results in an array of game rounds which may look something like the following:

const roundHistory = [
  {
    question: 'question1',
    submissions: [
      {
        explanation: 'answer1',
        player: { id: 'id1', name: 'player1' },
        votes: [
          { id: 'id2', name: 'player2' },
          { id: 'id3', name: 'player3' },
        ],
      },
      {
        explanation: 'answer2',
        player: { id: 'id2', name: 'player2' },
        votes: [{ id: 'id1', name: 'player1' }],
      },
      {
        explanation: 'answer3',
        player: { id: 'id3', name: 'player3' },
        votes: [],
      },
    ],
  },
  {
    question: 'question2',
    submissions: [
      {
        explanation: 'answer1',
        player: { id: 'id1', name: 'player1' },
        votes: [
          { id: 'id2', name: 'player2' },
          { id: 'id3', name: 'player3' },
        ],
      },
      {
        explanation: 'answer2',
        player: { id: 'id2', name: 'player2' },
        votes: [{ id: 'id1', name: 'player1' }],
      },
      {
        explanation: 'answer3',
        player: { id: 'id3', name: 'player3' },
        votes: [],
      },
    ],
  },
];

As you can see there are 3 players in the game since each round (index of the roundHistory array) has 3 submissions. Each submission has a property player which represents the player who submitted the submission. And then each submission has a property votes which is an array of the players who voted for that submission. Now my question:

How can I get the total received votes per player of all rounds?


What I’ve tried so far… I thought, first I’d get the total received votes per player per round like so:

const roundHistory = [{question:'question1',submissions:[{explanation:'answer1',player:{id:'id1',name:'player1'},votes:[{id:'id2',name:'player2'},{id:'id3',name:'player3'},],},{explanation:'answer2',player:{id:'id2',name:'player2'},votes:[{id:'id1',name:'player1'}],},{explanation:'answer3',player:{id:'id3',name:'player3'},votes:[],},],},{question:'question2',submissions:[{explanation:'answer1',player:{id:'id1',name:'player1'},votes:[{id:'id2',name:'player2'},{id:'id3',name:'player3'},],},{explanation:'answer2',player:{id:'id2',name:'player2'},votes:[{id:'id1',name:'player1'}],},{explanation:'answer3',player:{id:'id3',name:'player3'},votes:[],},],},];

const getTotalReceivedVotesPerPlayerInRound = (round) => {
  return roundHistory[round].submissions.map((s) => ({
    player: s.player,
    totalVotes: s.votes.length,
  }));
}

console.log(getTotalReceivedVotesPerPlayerInRound(0));

But I got stuck at adding all results of all rounds together. Note that I tried to simplify all used objects such as a player. In my application these are mostly classes for which I have several utility methods. One of them is the getTotalReceivedVotesPerPlayerInRound() method that I can use on a round (index of the roundHistory array).

How to open and close a search bar in reacatjs?

I need to open a very simple search bar in reactjs, and there is no closing button because I want to click on the same button to close it.

Here is some code I tried out but didn’t work.

  const [searchIsOpen, setSearchIsOpen] = useState(false);
  const search = () => {
    if (searchIsOpen) {
      setSearchIsOpen(true);
    } else {
      setSearchIsOpen(false);
    }
  };

<button onClick={search}
        className="absolute md:left-8 left-3 lg:left-2 top-6 md:top-8 cursor-pointer"> 
 </button>

And this element should open.

    <div>
  <input type="text" name="" id="" />
  </div>

thank you.

Getting a blank page after updating my react to v18

After I imports from reacts and rendering to app.js, I got a blank page though I just upgraded to react18. here is my code below.

     import React from 'react';
     import { createRoot } from 'react-dom/client';
     import { BrowserRouter } from 'react-router-dom';
     import App from './App';
     const container = document.getElementById('root');
     const root = createRoot(container);
     root.render( 
       <BrowserRouter>
         <App />
       </BrowserRouter>);

and i got this error below in my console

the above error occurred in the component:
at meta

at HomePage
at Routes (http://localhost:3000/static/js/bundle.js:40123:5)
at App
at Router (http://localhost:3000/static/js/bundle.js:40056:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:38865:5)

warning ……package.json: No license field

yarn start

But It shows

yarn start
arn run v1.22.10
arning ……package.json: No license field
node index.js

{
  "name": "mernbookingapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "Shakil",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "express": "^4.18.1"
  }
}

Firebase authentication using google/facebook with custom nodejs server

I am trying to integrate firebase authentication with my custom nodejs server. The email/password strategy is pretty straightforward as the admin sdk supports all the operations needed. However in the case of providers, the documentation instructs us to Handle the sign-in flow manually
and get some token from either google or facebook and then send it to our nodejs server.
So when the token arrives to our nodejs server the documentation provides some code that comes from the client sdk.

This is a sample from the firebase documentation

import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";

// Build Firebase credential with the Google ID token.
const credential = GoogleAuthProvider.credential(id_token);

// Sign in with credential from the Google user.
const auth = getAuth();
signInWithCredential(auth, credential).catch((error) => {
  // Handle Errors here.
  const errorCode = error.code;
  const errorMessage = error.message;
  // The email of the user's account used.
  const email = error.customData.email;
  // The AuthCredential type that was used.
  const credential = GoogleAuthProvider.credentialFromError(error);
  // ...
});

where the id_token (probably) comes from the request body.

This flow works just fine but it is using the client sdk in a nodejs server environment because the admin sdk that is inteded for such an environment does not support this kind of operation. So, is it ok to use both SDKs, where it is needed of course, in a nodejs server?

How to convert PowerPoint, PDF, and Word files to different slides like SlideShare?

I would like to be able to display PowerPoint slides.
How should I implement this?

How did a website like Slideshare actually implement this?

When you upload a PowerPoint, Word, or PDF file, each page is displayed as a slide, each of which is a div and contains the image tag of that page with different qualities.

How can I do this with the front-end and back-end? (the back-end is with PHP).
Is there a library for it?

Display form info on alert (html and javascript)

I currently have a form in which a user can put his name, age and the message and then I have a button to submit the message and it is supposed to show an alert with the form information but when I put the information and click the button nothing is happening (the alert doesn’t show). Here is the html form and javascript function code:

<form action="#" method="get">
        <fieldset>
            <legend>Informações do utilizador</legend>
            <label for="nome">Nome:</label>
            <input id="nome" name="nome" type="text" />
            <br />
            <label for="idade">Idade:</label>
            <select id="idade" name="idade">
                <option value="menor">&lt;18</option>
                <option value="jovem">18-21</option>
                <option value="jovemadulto">22-29</option>
                <option value="adulto">30-39</option>
                <option value="adultoavancado">40-49</option>
                <option value="idoso">&gt;=50</option>
            </select>
        </fieldset>
        <fieldset>
            <legend>Ideias para tornar um campus mais sustentável</legend>
            <label for="mensagem">Mensagem:</label><br />
            <textarea id="mensagem" name="mensagem" rows="10" cols="50" placeholder="Introduza a sua ideia">
                </textarea>
            <br />
            <input id="enviar" name="enviar" type="submit" onClick="submitForm()" value="Enviar">
            <script>
                function submitForm() {
                    var n = document.getElementById('nome').value;
                    var i = document.getElementById('idade').value;
                    var m = document.getElementById('mensagem').value;

                    alert("Nome: "+s+"n Idade: "+i+"n Mensagem: "+m);
                }
            </script>

            <input id="limpar" name="limpar" type="reset" value="Limpar" />
        </fieldset>
    </form>