Javascript data object is populated in a conditional check, but secondary output of specific object variables are undefined?

I know this is some weird async issue, but how would I output the “nid” value? I made a conditional statement to check if “data” is populated it does indeed contain something. So in the next statement I just want to output the internal object variables such as “nid”. I know its something to do with async, but I just want to output the variable I need.

Stop linking me to other “duplicate” questions or answers as the solution below does not work as shown in other questions!

console.log(JSON.stringify(data.nid));

enter image description here

enter image description here

Why is the message not disappearing after two hours when connected to my countdown timer written in JavaScript?

I want the Timer to display “Stream läuft gerade” for two hours after the countdown ended, and then to start the next countdown. For some reason that just doesn’t work/the text stays there forever/for way too long.

// Streamzeiten in UTC Zeit (Deutschland ist UTC)
const streamTimes = [
  { day: 1, hour: 17, minute: 0 },     // Montag
  { day: 2, hour: 17, minute: 0 },     // Dienstag
  { day: 3, hour: 17, minute: 0 },     // Mittwoch
  { day: 4, hour: 17, minute: 0 },     // Donnerstag
  { day: 5, hour: 18, minute: 0 },     // Freitag
  { day: 6, hour: 13, minute: 0 },     // Samstag
];

function getNextStreamTime() {
  const now = new Date();
  const currentDay = now.getUTCDay();
  const currentHour = now.getUTCHours();
  const currentMinute = now.getUTCMinutes();
  
  for (let i = 0; i < streamTimes.length; i++) {
    const streamTime = streamTimes[i];
    if (streamTime.day > currentDay || (streamTime.day === currentDay && streamTime.hour > currentHour) || (streamTime.day === currentDay && streamTime.hour === currentHour && streamTime.minute > currentMinute)) {
      return streamTime;
    }
  }

  // Wenn Keine weiteren Streams zu montag gehen
  return streamTimes[0];
}

function startCountdown() {
  const countdownElement = document.getElementById("countdown");
  
  const nextStreamTime = getNextStreamTime();
  const targetDate = new Date();
  targetDate.setUTCHours(nextStreamTime.hour, nextStreamTime.minute, 0, 0);
  
  const timer = setInterval(() => {
    const currentDate = new Date();
    const timeDifference = targetDate - currentDate;
    
    if (timeDifference <= 0) {
      clearInterval(timer);
      countdownElement.innerHTML = "Stream momentan Live";
      setTimeout(startCountdown, 2 * 60 * 60 * 1000); 
      return;
    }
    
    const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
    
    countdownElement.innerHTML = `${days} Tage, ${hours} Stunden, ${minutes} Minuten, ${seconds} Sekunden`;
  }, 1000);
}

startCountdown();

I expected it to work like that and have absolutely no idea why it isn’t working.

Issue with launchCameraAsync(): Possible unhandled promise rejection

I am trying to create a button in react native, that on being pressed opens the camera and allows the user to take a picture.

For this, I am using the expo image picker.

Here is my code:

import { View, Button, Alert } from "react-native";
import { useCameraPermissions, PermissionStatus, launchCameraAsync } from 'expo-image-picker';

const ImagePicker = () => {
  const [cameraPermissionInformation, requestPermission] = useCameraPermissions();

  const verifyPermissions = async () => {
    if (cameraPermissionInformation.status === PermissionStatus.UNDETERMINED) {
      const permissionResponse = await requestPermission();

      return permissionResponse.granted;
    };

    if (cameraPermissionInformation.status === PermissionStatus.DENIED) {
      Alert.alert(
        'Insufficient Permissions',
        'You need to grant camera permissions to use this app.'
      );
      return false;
    }

    return true;
  }

  const takeImageHandler = async () => {
    const hasPermission = await verifyPermissions();

    if (!hasPermission) {
      return;
    }

    const image = await launchCameraAsync({
      allowsEditing: true,
      aspect: [16, 9],
      // quality: 0.5,
    });
    console.log(image);
  };

  

  return (
    <View>
      <View>
        {/*Additional content to be added here*/}
      </View>
      <Button
        title="Take Image"
        onPress={takeImageHandler}
      />
    </View>
  )
};

export default ImagePicker;

When I run the app however, I receive this warning:

error

Why is this event listener function working on one class but not the other

I have x tables created with php and Ajax. When I call this function the first event listener works, but the second one does not, the classes all exist on various elements, any clue why?

I expect to add a class of selected_row to the row that has been clicked on, but this doesn’t happen for the rows with clickable-student-row, it does for clickable_time_row.

function update_clickable_times() {
// Select all elements with the "clickable-time-row" class
const clickableTimeRows = document.querySelectorAll('.clickable-time-row');

  // Select all elements with the "clickable-student-row" class
  const clickableStudentRows = document.querySelectorAll('.clickable-student-row');

  // Attach a click event listener to each element
  clickableTimeRows.forEach(row => {
    row.addEventListener('click', () => {
      // Perform desired actions when a row is clicked
      console.log('Row clicked!');
      // Additional code here...
      const id = row.id;

      // Remove the 'selected_row' class from all other rows
      clickableTimeRows.forEach(otherRow => {
        if (otherRow !== row) {
          otherRow.classList.remove('selected_row');
        }
      });

      // Assign the additional class 'selected_row' to the clicked row
      row.classList.add('selected_row');

      // Perform desired actions with the ID and the selected row
      console.log('Row clicked! ID:', id);
    });
  });

  // Remove the 'selected_row' class from all rows with the "clickable-student-row" class
  clickableStudentRows.forEach(row => {
    row.classList.remove('selected_row');
  });
  // Attach a click event listener to each element
  clickableStudentRows.forEach(row => {
    row.addEventListener('click', () => {
      // Perform desired actions when a row is clicked
      console.log('Row clicked!');
      // Additional code here...
      const id = row.id;

      // Remove the 'selected_row' class from all other rows
      clickableStudentRows.forEach(otherRow => {
        if (otherRow !== row) {
          otherRow.classList.remove('selected_row');
        }
      });

      // Assign the additional class 'selected_row' to the clicked row
      row.classList.add('selected_row');

      // Perform desired actions with the ID and the selected row
      console.log('Row clicked! ID:', id);
    });
  });

  // Remove the 'selected_row' class from all rows with the "clickable-student-row" class
  clickableTimeRows.forEach(row => {
    row.classList.remove('selected_row');
  });
}

Jest mock Promise call coverage not hit

I have issue with mock promise, even through the test pass, but when I open the test coverage does not hit it. What am I missing here? Thank you

Sample.js

export class SampleProvider {
  demoRequest(demo, sample) {
    return new Promise((resolve, reject) => {
      api
        .post(
         '/posts',
          {
            demo,
            sample,
          },
          'www.url.com'
        )
        .then((response) => resolve(response))
        .catch((error) => reject(error));
    });
  }
}

sample.test.js

import { SampleProvider } from '../SampleProvider';
const sample = new SampleProvider();

describe('Test SampleProvider-2', () => {
  afterEach(jest.clearAllMocks);

  const mockOffer = [
    {
      productId: 1,
      productName: 'testing',
    },
  ];

  it('should call demoRequest', function (done) {
    const mockData = { data: 'test' };
    jest.spyOn(sample, 'demoRequest').mockResolvedValue(mockData);
    cart.demoRequest(mockOffer, '123').then((res) => {
      expect(res).toBe(mockData);
      done();
    });
  });
});

secure videos url not playing in jw player react

I am trying to play signed url videos from JW Player in my React JS application using reactreact-jw-player library. After enabling the Secure Video URLs in JW player dashboard, no video is shown on the player, but as soon I disable this settings, the video is available to be played.

I tried to pass license key like below in my code, but still not working. Is there any thing I am doing wrong or any step that I am missing to set the JW Player in my react application.

<ReactJWPlayer
  playerId="4t00MwmP"
  playerScript="https://content.jwplatform.com/libraries/4t00MwmP.js"
  playlist={`https://cdn.jwplayer.com/v2/media/${mediaId}`}
  controls={false}
  licenseKey="+1bANyiZkaja12nPS2yV8ky+2NgQqilQmMg3/************/*********="
  isAutoPlay={false}             
  />

How can I modify a JavaScript code to randomly swap between pictures and links on page refresh?

i found this javascript code to get a different page everytime it is clicked.

function openLink() {
        var i = Math.floor(Math.random() * links.length);
        parent.location = links[i];
        return false;
      }

is there any way to add images to it?

the links are added by

links.push("link url")

expecting a way to add a picture as a path url maybe or adjusting the function

How to initialize Map without reinitializing when the page reloads?

I am trying to implement product cart in my e-commerce site.
Everything is working fine but only on one page.

The main idea, is to store products inside the Map data structure. So the key is a product id and the value is the other information about product.

simple explanation how it works. More detailed below

{ key -> id:
value -> {
           name: name,
           image: image,
           numberOfProducts: numberOfProducts,
           price: numberOfProducts
         }
}

As you can see, with this approach I have to initialize a variable with Map data structure in my App.js folder, whitch always updates when a new page opens and all data inside the Map clears, because it reinitialize the empty Map variable again with.

Here is the implementation of logic in Vanilla JS.

let cartMap = new Map;
localStorage.setItem("cartMap",JSON.stringify(cartMap))

let numberOfProducts = 1;
sessionStorage.setItem("amount",numberOfProducts)


function addToCart(name,id,price,image){

    if(cartMap.has(id)){

      cartMap.set(id,
        {
          name: name,
          image: image,
          numberOfProducts: ++numberOfProducts,
          price: price*numberOfProducts
        }
      )
    }
    else{

      numberOfProducts = 1;

      cartMap.set(id,
        {
          name: name,
          image: image,
          numberOfProducts: numberOfProducts,
          price: price*numberOfProducts
        }
      )
    }
    alerting()
}

const cartContent = document.querySelector('.modal-content-cart');

function alerting(){
  cartContent.innerHTML = Array.from( cartMap ).map(
    (([key,value]) => (
        `
        <div class="container-form-cart" id="cart_${key}">     
  
              <button onclick="removeItemFromCart(${key})" type="button" class="delete-product-from-cart">
                  <img src="/images/remove-image.png" alt="${key}">
              </button>
  
              <img class="cart-image" src="${value.image}" alt="">
  
              <h1 class="cart-name">
                ${value.name}
              </h1>
  
              <div class="amountOf">
                  <button onclick="increment(${key})" type="button" class="up">+</button>
                  <h1 class="total-price_${key}">${value.numberOfProducts}</h1>
                  <button onclick="decrement(${key})" type="button" class="down">-</button>
              </div>
  
              <h1 class="sum-price">
                  <p class="product-price-one_${key}">${value.price}</p>&#8381
              </h1>
  
        </div>
        
        `
      )
    )
  ).join("");
}

function increment(id){
  

  cartMap.set(
    
    id,
      {...cartMap.get(id),
        numberOfProducts:cartMap.get(id).numberOfProducts+1,
        price: cartMap.get(id).price+(cartMap.get(id).price/(cartMap.get(id).numberOfProducts))
      }
    )

  document.querySelector(".total-price_"+id).textContent = cartMap.get(id).numberOfProducts
  document.querySelector(".product-price-one_"+id).textContent = cartMap.get(id).price
}




function decrement(id){
  

  cartMap.set(
    id,
      {...cartMap.get(id),
        numberOfProducts:cartMap.get(id).numberOfProducts-1,
        price: cartMap.get(id).price-(cartMap.get(id).price/(cartMap.get(id).numberOfProducts))
      }
    )

  document.querySelector(".total-price_"+id).textContent = cartMap.get(id).numberOfProducts
  document.querySelector(".product-price-one_"+id).textContent = cartMap.get(id).price
}

function removeItemFromCart(id){
  cartMap.delete(id)
  document.querySelector("#cart_"+id).remove()
}


First try

I’ve tried to move from Map implementation into Html/map version, it basically means that my HTML will be that Map with keys as a name of the div class and object info inside it, but with this case I got stuck with the innerHTML -> I can’t make it create again and again one more div if i add product to the card, and even thou i will face same problem with page switching I think it’s not a good implementation of product Cart.

<div class="modal-wrapper">
     <form class="modal-content-cart animate">
       <!-- Here will come the cart -->

     </form>

</div>

Second try

I could’ve solve this problem with localStorage, but it can’t initialize inside a Map. We always have to first initialize the map then store it inside the localStorage, same with sessionStorage.

Conclusion

From all that thoughts and tries i came up with two questions. 

Is there an ultimate way to initialize Map without reinitialize when the page reloads? and the second question, How can I use my HTML as Map, so i will add HTML blocks one after another inside the div,without replacing them.
If you need additional information, don’t be shy, go ahead and ask it.

Radiobutton selection problem with dynamic question display

I’m trying to implement a dynamic question display feature in my React code, since I have a large number of questions with different input types, such as radiobuttons, text inputs, and dropdowns in the future. However, I’m encountering an issue with the functionality of radiobuttons.
The problem I’m facing is that when I try to select a radiobutton on the first card, nothing happens, but when I click an option on the second card, it selects the second option on the first card instead. Similarly, clicking an option on the third card doesn’t trigger any action, but it selects the third option on the first card.
I suspect that the problem lies in how I’m utilizing the “name” property, but despite my efforts, I haven’t been able to resolve the issue. Here’s my code:

import React, { useState } from "react";

const MapSurvey = () => {
  const questions = [
    {
      questionText: "one",
      answerOptions: [
        { answerText: "One", value: 1 },
        { answerText: "Two", value: 2 },
        { answerText: "three", value: 3 },
        { answerText: "four", value: 4 },
        { answerText: "five", value: 5 },
      ],
      answerType: "radio",
    },
    {
      questionText: "Two",
      answerOptions: [
        { answerText: "One", value: 1 },
        { answerText: "Two", value: 2 },
        { answerText: "three", value: 3 },
        { answerText: "four", value: 4 },
      ],
      answerType: "radio",
    },
    {
      questionText: "three",
      answerOptions: [
        { answerText: "One", value: 1 },
        { answerText: "Two", value: 2 },
        { answerText: "three", value: 3 },
        { answerText: "four", value: 4 },
        { answerText: "five", value: 5 },
      ],
      answerType: "radio",
    },
    {
      questionText: "input",
      answerType: "text",
    },
  ];

  const [answers, setAnswers] = useState({
    answer_0: "",
    answer_1: "",
    answer_2: "",
    answer_3: "",
  });

  console.log(answers);

  const handleChange = (e) => {
    setAnswers((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  return (
    <div className="w-full py-[2rem] px-4 bg-white">
      <div className="max-w-[800px] w-full mx-auto text-center flex flex-col">
        <form>
          {questions.map((question, idx) => (
            <div
              key={`question-no-${idx}`}
              className="border-2 border-gray-100 shadow-xl flex flex-col p-4 my-4 mb-6 rounded-lg"
            >
              <h2 className="text-2xl font-bold text-center py-4">
                {question.questionText}
              </h2>

              {question.answerType === "radio" ? (
                <>
                  {question.answerOptions.map((option, optionIdx) => (
                    <div
                      key={`answer_${idx}_option_${optionIdx}`}
                      className="mt-3"
                    >
                      <label htmlFor={`answer_${idx}`}>
                        <input
                          type={question.answerType}
                          name={`answer_${idx}`}
                          id={`answer_${optionIdx}`}
                          value={option.value}
                          className="hidden peer"
                          onChange={handleChange}
                        />
                        <div className="px-2 py-1 rounded-lg flex justify-left items-center font-medium text-black w-full sm:w-6/12 h-10 border-2 border-gray-200 peer-hover:border-[#00df9a] peer-checked:bg-[#00df9a] peer-checked:border-none peer-checked:text-white">
                          {option.answerText}
                        </div>
                      </label>
                    </div>
                  ))}
                </>
              ) : (
                <>
                  <input
                    name={`answer_${idx}`}
                    type={question.answerType}
                    id={`answer_${idx}`}
                    className="p-2 border-2 border-gray-200 hover:border-[#00df9a] focus:border-[#00df9a] w-full sm:w-6/12 h-10 rounded-lg text-black"
                    onChange={handleChange}
                  />
                </>
              )}
            </div>
          ))}
        </form>

        {/* full button on mobile */}
        <button className="bg-black text-[#00df9a]  w-[200px] rounded-md font-medium my-6 mx-auto px-6 py-3">
          Continua
        </button>
      </div>
    </div>
  );
};

export default MapSurvey;

What should I do to fix it?

I have a new login form, how do I ensure that browsers autofill the username and password used on the previous login form?

We’re upgrading ADFS on our servers (which causes the HTML markup to be completely different), and we want to make sure that after we switchover that users don’t have to enter in their username and password. I’ve looked all over the place and can’t find an answer regarding this particular scenario. How can I ensure that browsers still autofill the username and password on the new page?

All I can do is edit a script that gets executed on page load, which so far I’ve updated the names of the inputs to be the same as on the previous page, as well as set autocomplete=”on” for the form and input elements, which works on FireFox, but not on Chrome or Edge. Do I need to set the id’s of the inputs and/or form to be the same as the previous page as well? What all is necessary to make sure browsers still autofill on the new page?

Back4App: Can read/retrieve rows but can’t update/modify them

I know I am probably blind to something here, I am still new learning all this.
I am trying to modify a value in an object. the object is changing the way want it by checking console.log(user) but for some reason when the code gets to user.save() it just returns:

(https://i.stack.imgur.com/6tAUm.png)

async function healUser() {
  try {
    const customId = localStorage.getItem('Custom-User-ID');
    const query = new Parse.Query(Parse.User);
    query.equalTo("customId", customId);

    const user = await query.first();
    user.get("stats").health = user.get("stats").maxHealth;

    console.log(user)

    await user.save()
      .then((healedUser) => {
        healAlert();
      })
      .catch((error) => {
        console.error("Error: ", error);
      });

  } 
  catch (error) {
    console.error(error);
    // Handle any errors that occurred during healing process
  }
}

Code used to work for a good while, but suddenly I started getting this error. every other JS file that has the .save() returns similar error.

I would have guessed I reached my limit on the Back4App requests but I am just barely half way through it.

I tried:

  • comparing the object column names and values between the code and db
  • Changed the parse script header in my html to different versions
  • clearing all browsing data and restarting chrome/opera/firefox (tried live server in all 3)
  • checked the back4app logs (Parse error: Cannot modify user 0dvbwwVi6h.)
  • making a new back4app account just to test if its an account/keys issue
  • looking for a similar question/issue online

What is the ‘next’ function in Express middleware and how can it help redirect to another function?

I am new in Nodejs and working on Express js, Right now i am working on “middleware function” for specific routes,I want to know that “what is use of next”,means after autheticate what “next” function can do ? if we want to move/redirect to another function then how we can do ? And what is “checkAuthentication” ? Here is my current code

const express = require('express');
const app = express();

// Custom middleware function
const authMiddleware = (req, res, next) => {
  // Check if user is authenticated
  const isAuthenticated = checkAuthentication(req);
  
  if (isAuthenticated) {
    next();
  } else {
    // User is not authenticated, send an unauthorized response
    res.status(401).send('Unauthorized');
  }
};

// Middleware function is applied to specific routes
app.get('/protected', authMiddleware, (req, res) => {
  res.send('Protected Route');
});

// Route handler
app.get('/', (req, res) => {
  res.send('Home Page');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});


How to handle Buffer coming from NextJS backend API

I have a NextJS application where one of the backend API routes returns a JSON object that contains a buffer.

// nodeConfiguration has a nodeId property which is a buffer
res.status(200).json(nodeConfiguration);

When I receive this response on the frontend, I try to output the nodeId (data.nodeId.toString()) but what gets displayed is [object Object].

I tried to check if I am indeed getting a buffer on the frontend:

console.log(data.nodeId);

And on the dev console, I get this:

nodeId: {type: 'Buffer', data: Array(8)}

But when I use the isBuffer() to check:

Buffer.isBuffer(data.nodeId) ? 'buffer' : 'not buffer';

I get not buffer. I am confused and I don’t understand what’s happening here. What am I doing wrong and how do I properly pass a buffer to and from the backend?

Update each field in mongo db collection from map by providing key from another field

I have javascript object with key, values . In mongo collection need to set a field based on another field as key from object.

    const object = require('../file.json'); 

    const collection1 = db.collection('name1');
    const collection1Array = await db.collection('name1').find({"field1":{$exists:true}}).toArray();
  
    if (!collection1Array.length) return;
  
    const updatedList = collection1Array.map((doc) => ({
      updateMany: {
          filter: {"field1":{$exists:true}},
          update: {
            $set: {
              'field2': object[field1],
             },
         },
        }
    }));

    await collection1.bulkWrite(updatedList);

But this code is not updating correct values in database. Same value is getting updated for all records. For example, I have

object = {k1:v1,k2:v2,k3:v3}
collection1=[{field1=k1,...},{field1=k2...}...]
output=[{field1=k1,field2=v1,...},{field1=k2,field2=v1,...}...]
expected output=[{field1=k1,field2=v1,...},{field1=k2,field2=v2,...}...]

What might be going wrong here, any help ?