Passing a primitive to a then handler

This is an interesting observation that I have made when experimenting with promises in JS. Consider this code:

Promise.resolve(1).then(2).then(console.log);

This prints out 1 as its output. Why didn’t the native-implemented promise API throw an exception? What is the benefit of “skipping” the non-function argument when it is being ignored anyway? I woud really apreciate an answer

This post is found in MDN.

Store firebase document in a variable make me looses the references inside it

I’m trying to get a user document from Firebase, in order to put it as a global variable in re-use it in some functions. One of them is displaySavedPlaces() which allows to get a list of all the “places” documents the user has bookmarked. This is stored as an array of references in Firebase. Here is how it looks:
enter image description here

I store everything during onAuthStateChanged() : I get the document related to the user uid, and I store it in a variable called currentUser, also with user uid and a reference to the document if I need to call it again:

onAuthStateChanged(auth, async (userFirebase) => {
    if (userFirebase) {
        const userRef = doc(db, "users", userFirebase.uid);
        const userDoc = await getDoc(userRef);
        const userData = userDoc.data();
        currentUser = { uid: userDoc.id, ...userData, ref: userRef };
        const avatarRef = ref(avatarsImageRef, currentUser.customAvatar ?? "default-av.webp");
        currentUser.avatarUrl = await getDownloadURL(avatarRef);
    }
});

Then when I’m doing my function displaySavedPlaces later, I have an error from Firebase: Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?
It comes from the getDoc() function.

async function displaySavedPlaces(user) {
    console.log(user);
    elements.savedPlacesContainer.innerHTML = "";
    user.savedPlaces.forEach(async (elem) => {
        console.log(elem);
        const placeSnapshot = await getDoc(elem);
        const place = placeSnapshot.data();
        ...
    });
}

I was able to debug it by passing the saved places in a different variable than inside currentUser. The references seems to be lost/affected during the currentUser variable filling. It’s happening also when I’m simply doing currentUser = userData without creating any new object. Any idea why?

Browser has cached old JQuery script and clients must force reload page after Laravel app update on server

I have a Laravel application on my hosting. After update some functions in JQuery, clients must force reload page (ctrl + shift + R) for getting new functions. It seems like browser cached old JQuery script and don’t download new version of them.

How to force the browsers to force reload, when I add some new features in JQuery scripts in my Laravel app on my hosting?

Impossible to make a Text typer as ReactJS component working with StrictMode or not

I try to create a Text Typer component, where text is added character by character every 100ms.

Everything working good on production, but when I try to run it on dev env, impossible to make it work fine 2 intervals are running at the same time whatever the solution I try to implement (final typed text is ADFHJLNPRTVXZ)

I know that it come from React Strict mode since v18 to catch potential issue, but here it cause issue and I want the same behaviors on every environment.

I tested by addind a clearInterval on top, to stop the first trigger once the second is append. But it’s not workink :/

TextTyper

import React, { Dispatch, useEffect, useRef, useState } from 'react';

export type TextTyperProps = {
  text: string,
  /** Do not forget to wrap it under `useCallback` to avoid refresh the `useEffect` dependencies */
  onTextTyped?: Dispatch<void>,
  intervalTime?: number
};

export const TextTyper = ({ text, onTextTyped, intervalTime = 100 }: TextTyperProps) => {
  const [textTyped, setTextTyped] = useState('');
  const indexRef = useRef(0); // Keep index stored n a ref
  const intervalId = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {

    // Re-init all state when useEffect is called
    setTextTyped("");
    indexRef.current = 0;
    // Clean current interval in case text is udpated before typed completly, or useEffect is runned twice in dev mode
    if (intervalId.current) {
      clearInterval(intervalId.current);
    }

    // Select and type the next chat
    const typeNextChar = () => {
      if (indexRef.current < text.length) {
        setTextTyped((currentText) => {
          const nextChar = text.charAt(indexRef.current);
          console.log(`${indexRef.current}/${text.length} => ${currentText}[${nextChar}] `)
          indexRef.current++;
          return currentText + nextChar;
        });
      } else {
        // Once the text is completly typed, stop interval
        if (intervalId.current) {
          clearInterval(intervalId.current);
        }
        // And propagate
        onTextTyped?.();
      }
    };

    // Start a new interval
    intervalId.current = setInterval(typeNextChar, intervalTime);

    // Clear interval on unmount
    return () => {
      if (intervalId.current) {
        clearInterval(intervalId.current);
      }
    };
  }, [text, onTextTyped, intervalTime]);

  return <div>{textTyped}</div>;
};

Test Component

"use client"

import { useCallback, useState } from "react";
import { TextTyper } from "~/components/ui/TextTyper";



export default function TestTextTyper() {

  const [text, setText] = useState<string>("");
  const [isDone, setDone] = useState<boolean>(false);
  // Additional feature to force reload if ask for the same text
  const [lastUpdate, setLastUpdate] = useState<number>(0);


  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const revered = alphabet.split('').reverse().join('');
  const handleClick = (newText: string) => {
    setDone(false);
    setText(newText);
    setLastUpdate(Date.now())
  }
  const handleTextTyped = useCallback(() => {
    console.log("Text typing complete");
    setDone(true)
  }, []);

  return (
    <div>
      <button onClick={() => { handleClick(alphabet) }}>{alphabet}</button>
      <button onClick={() => { handleClick(revered) }}>{revered}</button>
      <TextTyper key={lastUpdate} text={text} onTextTyped={handleTextTyped} />
      {isDone && "DONE"}
    </div>
  );
}

When I click on the first button I got those logs (and we see that 2 interval are running on the same time)

TextTyper.tsx:30 0/26 => [A] 
TextTyper.tsx:30 1/26 => [B] 
TextTyper.tsx:30 2/26 => A[C] 
TextTyper.tsx:30 3/26 => A[D] 
TextTyper.tsx:30 4/26 => AD[E] 
TextTyper.tsx:30 5/26 => AD[F] 
TextTyper.tsx:30 6/26 => ADF[G] 
TextTyper.tsx:30 7/26 => ADF[H] 
TextTyper.tsx:30 8/26 => ADFH[I] 
TextTyper.tsx:30 9/26 => ADFH[J] 
TextTyper.tsx:30 10/26 => ADFHJ[K] 
TextTyper.tsx:30 11/26 => ADFHJ[L] 
TextTyper.tsx:30 12/26 => ADFHJL[M] 
TextTyper.tsx:30 13/26 => ADFHJL[N] 
TextTyper.tsx:30 14/26 => ADFHJLN[O] 
TextTyper.tsx:30 15/26 => ADFHJLN[P] 
TextTyper.tsx:30 16/26 => ADFHJLNP[Q] 
TextTyper.tsx:30 17/26 => ADFHJLNP[R] 
TextTyper.tsx:30 18/26 => ADFHJLNPR[S] 
TextTyper.tsx:30 19/26 => ADFHJLNPR[T] 
TextTyper.tsx:30 20/26 => ADFHJLNPRT[U] 
TextTyper.tsx:30 21/26 => ADFHJLNPRT[V] 
TextTyper.tsx:30 22/26 => ADFHJLNPRTV[W] 
TextTyper.tsx:30 23/26 => ADFHJLNPRTV[X] 
TextTyper.tsx:30 24/26 => ADFHJLNPRTVX[Y] 
TextTyper.tsx:30 25/26 => ADFHJLNPRTVX[Z] 
page.tsx:24 Text typing complete

It takes a long time to open the react project on localhost

When I want to open the project (or any react project) that I created with create-react-app in Visual Studio Code with npm start on localhost, it takes 5 minutes to open. On a similar issue, someone showed a network setting in the developer tools section, but that setting is already disabled for me (network throttling , (React app taking too much time for loading on local system)).

I deleted Vs Code, plugins and node.js and reinstalled it from scratch, I did everything but I couldn’t find a solution. It still opens very late.

Why do the created elements desappear from the webseite directly after their creation?

After input of:
Number
Text (which to be added in the div elements as text)
Select (Div or Section)

and after clicking on the Create-Button

the given number of divs will appear in the section.

This occur too but like I said all those created div elements disappear afterwards.

I changed the code several time but without any success 🙁

//HTML
<!DOCTYPE html>
<html>
<head lang="de">
  <title>Kontaktlistenbeispiel</title>
  <link rel="stylesheet" href="mainWeek12Challenge6.css" >
</head>
<body>
  <form action="">
    <input type="number" name="elements" class="input" placeholder="Number Of Elements" />
    <input type="text" name="texts" class="input" placeholder="Elements Text" />
    <select name="type" class="input">
      <option value="Div">Div</option>
      <option value="Section">Section</option>
    </select>
    <input type="submit" name="create" value="Create" />
    <div class="results"></div>
  </form>

  <script src="main6.js"></script>
</body>
</html>

// JS
const formEl = document.querySelector('form');
const numberInputEl = document.querySelector('input[type="number"]');
const textInputEl = document.querySelector('input[type="text"]');
const resultSection = document.querySelector('.results');
const selectionEle = document.querySelector('select');
const containerEl = document.createElement(selectionEle.value);
containerEl.style.cssText = "display: flex; justify-content: center; gap:10px;";

formEl.addEventListener('submit', constructElements);

function constructElements() {
    const containerEl = document.createElement(selectionEle.value);
    containerEl.style.cssText = "display: flex; justify-content: center; gap:10px;";
    let i = 0;
    while(i < parseInt(numberInputEl.value)) {
        const currDiv = document.createElement('div');
        currDiv.className = 'newDiv';
        currDiv.textContent = textInputEl.value;
        containerEl.appendChild(currDiv);
        i++;
    }

    resultSection.appendChild(containerEl);
}

How to create a Framer Motion animation with extremely slow start and end?

I’m trying to create an animation using framer-motion that will start slowly and especially end very, very slowly. Looking for a similar effect like on this website: https://wheelofnames.com/

I’ve experimented with various easing functions, and the closest I’ve come to the desired effect is by using the easing function [1, 0, 0, 1]. However, this doesn’t quite capture the extremely slow ending I’m looking for.

import { motion } from 'framer-motion';

function Home() {
  return (
    <motion.div
      style={{ backgroundColor: 'red', width: '5em', height: '5em' }}
      animate={{
        x: `50em`,
      }}
      transition={{
        type: 'tween',
        duration: 1,
        ease: [1, 0, 0, 1],
      }}
    />
  );
}

export default Home;

How to handle division of a very small numerator?

I’m developing a JavaScript calculator and facing an issue with the division operation. When very small numerators are divided by large denominators, the result becomes “0”. This isn’t the desired behavior. Ideally, the calculator should either:

  • Display a more informative message (e.g., “Number too small to divide”).
  • If possible, overcome this limitation and continue dividing.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Approaching Zero</title>
</head>
<body>
    <script>
        const result = 1.2e-321 / 99999999999999;
        console.log(result);
    </script>
</body>
</html>

I thought it would continue processing despite how small it is, but it turns out it’s not enough for precision and accuracy.

How to break recieve messages for 20 minutes after recieve for one time?

I have a websocket client that listens for incoming messages.
When a name is received, which is what I’m waiting for, it should be printed immediately in the console. It happens that the same name is sent from the server several times within minutes. At this point I would like to take a break of 20 minutes for this name. but not for other names. I’m very grateful for any help as I’m still learning.

This is a snippet from my client.which also works in my client


socket.addEventListener("message", event => {
event.data.text()
.then(dat=> {if(dat.includes('examplehere')) {
var A =  JSON.parse(txt.replace(/.*?({.*}).*/, "$1")) 
const Name = A.N
} else   
 return;
           
 
if(Name === 'Jhon'){
console.log("Name:"+Name)
}
if(Name === 'Julia'{
console.log("Name:"+Name)
}

})})

Generic typing is not getting assigned

I was trying generic typing, but it was throwing the below error. I am new to typescript. Please help me to understand the below error.

Property 'city' does not exist on type 'Person | MyLocation'.

In the following example, I have given the type as Person or MyLocation. In the output, I am able to get the given(city/sex) value. However output.city gives me propery city doesn’t exit error. Also when i try to destruct const { city } = identity<Person | MyLocation>({city: ‘SA’, sex: ‘Male’}); it return same error

Typescript Playground Example

interface Person {
  name: string;
  age: number;
}

interface MyLocation {
  city: string;
  sex: string;
}

function identity<Type>(arg: Type): Type {
  return arg;
}
        
const output = identity<Person | MyLocation>({city: 'SA', sex: 'Male'});

console.log(output.city)

Creating dynamic json object in Javascript

I have created this object structure

 [
    [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
    ],
    [
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ],
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ],
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ],
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ],
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ],
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ],
    [
    {
    "start_time":"02:00",
    "end_time":"06:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    },
    {
    "start_time":"00:00",
    "end_time":"00:00"
    }
    ]
    ],
    [
    [
    "morning",
    "afternoon",
    "evening"
    ],
    [
    "morning",
    "afternoon",
    "evening"
    ],
    [
    "morning",
    "afternoon",
    "evening"
    ],
    [
    "morning",
    "afternoon",
    "evening"
    ],
    [
    "morning",
    "afternoon",
    "evening"
    ],
    [
    "morning",
    "afternoon",
    "evening"
    ],
    [
    "morning",
    "afternoon",
    "evening"
    ]
    ]
    ]

using this below code

Code :

   var days=[];
          var slotstime=[];
          var slotsMonday=[];
          var slotsTuesday=[];
          var slotsWednesday=[];
          var slotsThursday=[];
          var slotsFriday=[];
          var slotsSaturday=[];
          var slotsSunday=[];
          var slots=[];
          var result=[];
          var mondayTime=[];
          var tuesdayTime=[];
          var wednesdayTime=[];
          var thursdayTime=[];
          var fridayTime=[];
          var saturdayTime=[];
          var sundayTime=[];
          if(this.MondayChecked)
          {
            days.push('Monday');
            mondayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            mondayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            mondayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsMonday.push('morning');
            slotsMonday.push('afternoon');
            slotsMonday.push('evening');
            slotstime.push(mondayTime);
          }
          if(this.TuesdayChecked)
          {
            days.push('Tuesday');
            tuesdayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            tuesdayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            tuesdayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsTuesday.push('morning');
            slotsTuesday.push('afternoon');
            slotsTuesday.push('evening');
            slotstime.push(tuesdayTime);
            
          }
          if(this.WednesdayChecked)
          {
            days.push('Wednesday');
            wednesdayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            wednesdayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            wednesdayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsWednesday.push('morning');
            slotsWednesday.push('afternoon');
            slotsWednesday.push('evening');
            slotstime.push(wednesdayTime);
          }
          if(this.ThursdayChecked)
          {
            days.push('Thursday');
            thursdayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            thursdayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            thursdayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsThursday.push('morning');
            slotsThursday.push('afternoon');
            slotsThursday.push('evening');
            slotstime.push(thursdayTime);
          }
          if(this.FridayChecked)
          {
            days.push('Friday');
            fridayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            fridayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            fridayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsFriday.push('morning');
            slotsFriday.push('afternoon');
            slotsFriday.push('evening');
            slotstime.push(fridayTime);
          }
          if(this.SaturdayChecked)
          {
            days.push('Saturday');
            saturdayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            saturdayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            saturdayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsSaturday.push('morning');
            slotsSaturday.push('afternoon');
            slotsSaturday.push('evening');
            slotstime.push(saturdayTime);
          }
          if(this.SundayChecked)
          {
            days.push('Sunday');
            sundayTime.push({'start_time':this.appSetting.morningStartTime,'end_time':this.appSetting.morningEndTime});
            sundayTime.push({'start_time':this.appSetting.afternoonStartTime,'end_time':this.appSetting.afternoonEndTime});
            sundayTime.push({'start_time':this.appSetting.nightStartTime,'end_time':this.appSetting.nightEndTime});
            slotsSunday.push('morning');
            slotsSunday.push('afternoon');
            slotsSunday.push('evening');
            slotstime.push(sundayTime);
          }
          slots.push(slotsMonday);
          slots.push(slotsTuesday);
          slots.push(slotsWednesday);
          slots.push(slotsThursday);
          slots.push(slotsFriday);
          slots.push(slotsSaturday);
          slots.push(slotsSunday);
          result.push(days);
          result.push(slotstime);
          result.push(slots);
   

result of console variable
console.log(result);

but i want to make dynamic structure like this

{
"Days":{
"MONDAY": {
   "Morning":{ 'start_time':this.appSetting.morningStartTime },
   "Afternoon": { 'start_time':this.appSetting.afternoonStartTime},
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},
"TUESDAY": {
   "Morning":{ 'start_time':this.appSetting.morningStartTime },
   "Afternoon": { 'start_time':this.appSetting.afternoonStartTime},
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},
"WEDNESDAY": {
   "Morning":{ 'start_time':this.appSetting.morningStartTime },
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},
"THURSDAY": {
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},
"FRIDAY": {
   "Morning":{ 'start_time':this.appSetting.morningStartTime },
   "Afternoon": { 'start_time':this.appSetting.afternoonStartTime},
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},
"SATURDAY": {
   "Morning":{ 'start_time':this.appSetting.morningStartTime },
   "Afternoon": { 'start_time':this.appSetting.afternoonStartTime},
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},
"SUNDAY": {
   "Morning":{ 'start_time':this.appSetting.morningStartTime },
   "Afternoon": { 'start_time':this.appSetting.afternoonStartTime},
   "Evening": { 'start_time':this.appSetting.nightStartTime}
},

but this structure should be dynamically created based on the condition above so that i can access days and its slots timings.

Any solution Thanks

Access to XMLHttpRequest at ‘https://a/socket.io/?token= from origin has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ [duplicate]

Access to XMLHttpRequest at ‘https://vm-node.azurewebsites.net/socket.io/?token=Bearer [REDACTED]&userid=tom%40mailinator.com&EIO=3&transport=polling&t=OsOUdZe’ from origin ‘http://localhost:4202’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Client side

var iosocket = io('https://vm-node.azurewebsites.net', {
  query: {
    token: '',
    userid: ''
  }
});

Is transpling python library to javascript feasible and good approach to share data between multilanguage components?

I’m looking for a way to share common data sources for a system along many node / python services.

Currently I’ve data source lib written in python, and to avoid latencies I’d like not to create REST api with it but instead transpile it on the fly to JS, publish it as npm lib so all of our services can use it. It sounds like a good idea in my head but I’d like to hear opinions and experiences with this approach, if it’s feasible, and any tools you’d recommend for doing this.

EDIT: library consists of enum and dicts only

Expo Contact: Request Permission to access contact if it is status is denied

I have a contact component that works as expected, but if a user initially denies the request to grant my app access to their contact the request is not being asked again, the contact modal instead appears empty:

  useEffect(() => {
    (async () => {
      const { status } = await Contacts.requestPermissionsAsync()

      if (status === "granted") {
        const { data } = await Contacts.getContactsAsync({
          fields: [Contacts?.Fields?.PhoneNumbers],
        });
        if (data.length > 0) {
          setContacts(data);
        }
      }
    })();
  }, []);