How to prevent/handle auto redirection on api calls with fetch

I am trying to access the api but for accessing the api I need token so When I try to hit the api it redirects to the auth page.

I can see the redirection is happening in the network tab.

is there any way to prevent this?

I wanted to get the 302 error code when I first hit the api(its giving 302 but with fetch/Redirect) but because of automatic redirection its throwing error and going to error block always.

fetch(url, { method: 'POST', redirect: 'follow'})
.then(response => {
    // handle 302 response
})
.catch(function(err) {
    console.info(err);
});

Function parameter in constructor

I have a class which takes as a parameter a function which conforms to an interface. The class later calls this function with a given input.

In the interface an input is always required, but other parameters are also allowed, though optional. I want to provide these extra paramters when creating an instance – how should I do this?

I have considered adding an args parameter in the constructor which will be applied to the function call, but this seems ugly and detaches the parameters from the function. I also considered creating an intermediate function which takes the single input parameter and passes it on to the function with args, but again this seems messy – I’d like to encapsulate everything inside the class and provide all configuration of the resulting instance when it is constructed.

interface IThingAction {
    (input: string, ...args: any[]): boolean;
}

let printInput: IThingAction = (input: string) => {
    console.log(input);
}

let repeatInput: IThingAction = (input: string, iterations: number) => {
    for (var i = 0; i < iterations, i++) {
        console.log(input);
    }
}

class Thing {
    action: IThingAction;

    constructor(action: IThingAction) {
        this.action = action;
    }

    doAction(input: string): boolean {
        return this.action(input);
    }
}

let printer = new Thing(printInput);
let repeater = new Thing(repeatInput); // I'd like to provide extra parameters here

adding classList.toggle for created elemnts with javaScript DOM

i want to make js dark mode toggle with click event but it works
with html elemnts but itsn’t works with created elemnts with javaScript using DOM.

let body = document.querySelector(`body`);
let input = document.querySelector(`.input`);
let addBtn = document.querySelector(`.add`);
let form = document.querySelector(`.form`);
let container = document.querySelector(`.tasks`);

form.addEventListener(`submit`, (e) => {
  e.preventDefault();
  const task = input.value;
  if (!task) {
    window.alert(`please fill the input!`);
  } else {
    const taskEl = document.createElement(`div`);
    taskEl.classList.add(`task`);

    const taskContentEl = document.createElement(`div`);
    taskContentEl.appendChild(document.createTextNode(task));
    taskEl.appendChild(taskContentEl);
    container.appendChild(taskEl);

    input.value = ``;
  }
});

function darkMode() {
  let darkBtn = document.querySelector(`.btn`);

  darkBtn.onclick = () => {
    form.classList.toggle(`formDark`);        
    input.classList.toggle(`inputDark`);
    body.classList.toggle(`bodyDark`); 
     //here is the code that's not works 
    taskEl.classList.toggle(`inputDark`); };
}
darkMode();

Sending content from TinyMCE to Airtable

I’ve implemented TinyMCE on an app I’ve created, and would like to have it submit the textarea’s content to Airtable on button click. The thought process is: retrieve the textarea data, pull some basic information about the user and the Airtable table I’d like to write to, and then create a new record. I’m running into trouble getting the function up and running, though; can anyone take a look at the code below and see where I’m going wrong?

For reference, here’s what I have so far:

Header

<script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/airtable.umd.min.js"></script>
<script src="https://cdn.tiny.cloud/1/myapikeyhere/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
      tinymce.init({
        selector: '#mytextarea',
        branding: false
      });
</script>

Body

<textarea id="mytextarea">Start typing here!</textarea><br><br>
<button onclick="sendtoAirtable()" class="button">Create Post</button>
 
<script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>
<script>
    function sendtoAirTable(){
        var data = tinymce.instances.mytextarea.getData();
        saveToAirTable(data);
    
        function saveToAirTable(data){
            var userId = window['logged_in_user']['airtable_record_id']
            var base = new Airtable({apiKey: 'myapikey'}).base('airtablebaseid');
        }
    
        base('tablename').create([
            {
               "fields": {
                  "Content":data,
                  "User": [
                     userId
                  ]
               }
            }
        ], function(err, records) {
            if (err) {
                 console.error(err);
                 return;
                }
         });
    }
</script>

How to return a Promise in a Javascript async function? Why does Async method not wrap the returned Promise?

I have the following code. My intention is to start a task (which involves a few await calls). When it finishes starting it, result will come in later so I want to return another Promise so the app knows when the result comes in:

async function startSomethingAsync() {
    await new Promise(r => globalThis.setTimeout(r, 1000));
    console.log("Task started");

    const finishedPromise = new Promise<number>(r => {
        globalThis.setTimeout(() => r(100), 3000);
    });
    return finishedPromise;
}

(async() => {
    // resultPromise is number instead of Promise<number>
    const resultPromise = await startSomethingAsync();

    // My intention: update UI after starting the task
    console.log("Task started");

    // Then when the result is there, do something else
    // Currently this is not compiled because resultPromise is not a Promise
    resultPromise.then(r => console.log("Result arrived: " + r));
})();

However the above code does not work. Somehow resultPromise is number (100 after resolved) instead of Promise<number>. TypeScript also recognize startSomethingAsync returning Promise<number> instead of Promise<Promise<number>>.

Why is this happening? Shouldn’t the async method wrap another Promise outside of the returned Promise? How do I achieve what I am trying to do and is it a “good” pattern?

What is the difference between join() and enter() in d3.js?

I have been getting into data visualization with d3.js, but there is one thing that I have not been able to wrap my head around. What is the difference between d3.join() and d3.enter()? Is enter() to be used mainly for dynamic data? Or is join() an overarching method that contains enter(), exit(), and update()?

How can I make different levels for a game? Would I have to make different classes?

I already have a sketch.js file with some gameStates.

var gameState = "wait";

I added conditional statements such as:

 if(gameState == "wait"){
    background(backgroundImg);
  textSize(50);
  fill("blue");
  text("Project42 Own",250,400);
  startButton.visible = true;
  gun.visible = false;
  backBoard.visible = false;
  }

Below is the code that has level 1, wait, play and end gameState:

function draw() {
  if(gameState == "wait"){
    background(backgroundImg);
  textSize(50);
  fill("blue");
  text("Project42 Own",250,400);
  startButton.visible = true;
  gun.visible = false;
  backBoard.visible = false;
  }
  if(mousePressedOver(startButton)&& gameState == "wait"){
    gunSound.play();
    gunSound.setVolume(0)
    gameState = "play";
  }
  if(gameState == "play"){
    background("#BDA297")
    fill("red");
    textSize(30);
  text("Score:" + score + " ",300,100);
  fill("green");
  text("Life:" + life + " ",800,100)
  gun.y=mouseY  
  startButton.visible = false;
  gun.visible = true;
  backBoard.visible = true;
 
 if(keyDown("SHIFT")){
   shootBullets();
 }
 if (frameCount % 80 === 0) {
  drawBlueBubble();
}

if (frameCount % 100 === 0) {
  drawRedBubble();
}

if(blueBubbleGroup.collide(bulletGroup)){
  handleBubbleCollision(blueBubbleGroup);
  score +=5;
}

if(redBubbleGroup.collide(bulletGroup)){
  handleBubbleCollision(redBubbleGroup);
  score += 10;
}
if (blueBubbleGroup.collide(backBoard)){
  handleGameover(blueBubbleGroup);
}

if (redBubbleGroup.collide(backBoard)) {
  handleGameover(redBubbleGroup);
}
  }
  if (life == 0) {
  gameState == "end"
}
if(gameState == "end"){
  background(gameOverImg)
  redBubbleGroup.hideEverything()
  blueBubbleGroup.hideEverything();
}
  drawSprites();
}

However, I now want to make level 2 in which there will be more obstacles. Also, I’m not a professional coder so please be clear in your answer.

How to make periodic api calls even when my web app is closed in chrome

My usecase:
I have to make rest api call for every 2 hours of interval even my web application is not running in chrome.

I have tried with periodic sync feature in service worker for my web application.
Currently periodic sync in chrome will dispatch events based on many criteria ( power save mode, presence for network, site engagement score…). Also with min interval of 12 hours to dispatch event.

Is there any way to make periodic api calls even web app is not running (other than periodic background sync) ?.

Removing a class from an element when other element is being clicked

I have a sticky navbar that contains 4 divs with class .menu-container. Each one of these divs contains an image, a text and a div with classes .rectangle and .hidden. Basically, my goal is to remove the class .hidden when a specific element of .menu-container is being clicked.
I tried different ways to remove the class. One of them was to add rectangle[el].classList.remove(‘hidden’) but I get undefined and strangely the rectangle appears in the browser, but when I check in the console I get this error ‘Uncaught’.
Here’s the code to make it clear:

"use strict";

const rectangle = document.querySelectorAll(".rectangle");

window.addEventListener('DOMContentLoaded', event => {
  document.querySelectorAll('.menu-container').forEach(el =>             
    el.addEventListener('click', event => {
      rectangle[el].classList.remove('hidden');
      console.log('clicked');
    }
   )
  )
})
.sticky {
  display: flex;
  justify-content: center;
  flex-shrink: 1;
  min-height: 70px;
  padding: 0 287px 0;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.22);
  background-color: $light--black;
  // align-items: center;
  // align-items: stretch;
  


  .menu-container {
      display: inline-flex;
      flex-direction: column;
      align-items: center;


      &:hover {
        .text-sticky {
          color: white;
        }
        .icon-coffee--grey {
          display: none;
        }
        .icon-coffee--white {
          display: block;
        }
        .icon-capsules--grey {
          display: none;
        }
        .icon-capsules--white {
          display: block;
        }
        .icon-mousse--grey {
          display: none;
        }
        .icon-mousse--white {
          display: block;
        }
        .icon-machines--grey {
          display: none;
        }
        .icon-machines--white {
          display: block;
        }
      }

      @include between(1, 3) {
        position: relative;
        &::after {
          content: "";
          position: absolute;
          width: 0.5px;
          right: -3px;
          min-height: 41px;
          background-color: $white;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .icon-coffee {
        width: 44px;
        height: 18px;
        // margin: 7px 76px 5px 77px;
        margin: 18px 77px 5px;
      }
      .icon-coffee--white {
          display: none;
      }
      .icon-capsules {
        width: 49px;
        height: 14px;
        // margin: 8px 72px 8px 75px;
        margin: 19px 74px 8px;
      }
      .icon-capsules--white {
          display: none;
      }
      .icon-mousse {
        width: 25px;
        height: 24px;
        margin: 13px 86px 4px;
      }
      .icon-mousse--white {
          display: none;
      }
      .icon-machines {
        width: 15px;
        height: 26px;
        margin: 11px 91px 4px;
      }
      .icon-machines--white {
        display: none;
      }
  
      .text-sticky {
        font-size: 12px;
        min-height: 16px;
        font-family: "NespressoLucas-SemiBd";
        margin: 0 0 9px 0;
        line-height: 1.33;
        letter-spacing: 0.34px;
        text-transform: uppercase;
        color: grey;
        text-align: center;
      }

      .rectangle {
        width: 100%;
        height: 4px;
        background-color: $brown;
      }

        .hidden {
          display: none;
        }

    }
}
...
    <div class="sticky">
      <div class="menu-container">
        <a class="coffee-icon" href="">
          <img class="icon-coffee icon-coffee--grey" src="assets/icon-coffee-grey.svg" alt="">
          <img class="icon-coffee icon-coffee--white" src="assets/icon-coffee-white.svg" alt="">
        </a>
        <p class="text-sticky">les cafés</p>
        <div class="rectangle hidden"></div>
      </div>
      <div class="menu-container">
        <a class="capsules-icon" href="">
          <img class="icon-capsules icon-capsules--grey" src="assets/icon-capsules-grey.svg" alt="">
          <img class="icon-capsules icon-capsules--white" src="assets/icon-capsules-white.svg" alt="">
        </a>
        <p class="text-sticky">les capsules</p>
        <div class="rectangle hidden"></div>
      </div>
      <div class="menu-container">
        <a class="mousse-icon" href="">
          <img class="icon-mousse icon-mousse--grey" src="assets/icon-mousse-grey.svg" alt="">
          <img class="icon-mousse icon-mousse--white" src="assets/icon-mousse-white.svg" alt="">
        </a>
        <p class="text-sticky">les technologies</p>
        <div class="rectangle hidden"></div>
      </div>
      <div class="menu-container">
        <a class="machines-icon" href="">
          <img class="icon-machines icon-machines--grey" src="assets/icon-machines-grey.svg" alt="">
          <img class="icon-machines icon-machines--white" src="assets/icon-machines-white.svg" alt="">
        </a>
        <p class="text-sticky">les machines</p>
        <div class="rectangle hidden"></div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

Modifying all images from div using css and Javascript

So i have a div with a lot of images:

<div id="d1">
    <img id="img1" src="resources/square.png"/>
    <img id="img2" src="resources/square.png"/>
    ...
</div>

my css file looks like this:

#d1 img {
    width: 5%;
}

So, instead of looping over all the images, is it possible to modify the width attribute above using javascript? (I want to modify every image’s width)

Overflow-x:hidden can still scroll

I have a page where you can scroll left on mobile. I have already tried .js, max-width 100%, overflow-x:hidden (on both body and html), all with !important.
It only happens on this page, and only on mobile.

How do i fix this? Im open to any ideas

Problems with element.click() in puppeteer

I got following Problem. If I run this code I get this error message and I cant seem to fix it.

Uncaught Error Error: Evaluation failed: TypeError: Cannot read
properties of undefined (reading ‘click’)
at _evaluateInternal (c:UsersNamenode_modulespuppeteerlibcjspuppeteercommonExecutionContext.js:221:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

const puppeteer = require('puppeteer');
const url = "https://www.zalando.de/nike-sportswear-blazer-mid-77-sneaker-high-ni115n001-a13.html";

async function initBrowser() {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto(url);
    await page.screenshot({ path: 'example.png' });
    return page;
}
async function addToCart(page) {
    await page.$eval('span[class="piG9a1 _1IcNq Uxq3DH QylWsg JCuRr_ RYghuO _7Cm1F9 ka2E9k uMhVZi FxZV-M"]', element => element.click());
    await page.$$eval('.example', elements => {
        const element = elements.find(element => element.innerHTML === '39');
        element.click();
    });
    await page.$eval('button[class="DJxzzA u9KIT8 uEg2FS U_OhzR ZkIJC- Vn-7c- FCIprz heWLCX JIgPn9 LyRfpJ pxpHHp Md_Vex NN8L-8 GTG2H9 MfX1a0 WCjo-q EKabf7 aX2-iv r9BRio mo6ZnF E6Km4r"]', element => element.click());
}

async function checkout() {
    const page = await initBrowser();
    await addToCart(page);
}


checkout();

Socket.IO fetchSockets() returning an empty array from a room

So I’m trying to get the connected sockets of a Room but I’m getting a empty list.

Code:

client.on('check join', async code =>{
    const sockets = await io.in(code).fetchSockets()
    console.log(sockets)
})
client.on('check join', async code =>{
    const sockets = await io.in(code).fetchSockets()
    console.log(sockets)
})

This is the code where I join the client to a room.

    client.on('check', (room_code)=>{
        activeRooms.forEach((v, i)=>{
            if (v == room_code){
                client.emit('check', {status: false,code: null})
                return false
            }
        })
        activeRooms.push({
            game: 'rps-classic',
            max_players: 2,
            code: room_code
        })
        client.emit('check', {status: true, code: room_code});client.join(room_code);return true
    })

The room code is extracted from a Input inside a form and is 4 digits including numbers and letters.

I’m testing joining a room and then trying the fetchSockets but do not seems to work.

( Yeah, room_code and code are the same. )