Why await/async in Javascript does not work as expected?

As a way to learn async/await in Javascript, I created the following JSFiddle sample code

async function func1() {
  return await setTimeout(() => {
    console.log('execute func1');
  }, 5000);
}

async function func2() {
  return await setTimeout(() => {
    console.log('execute func2');
  }, 2000);
}

async function mainFunc() {
    await func1();
  await func2();

  console.log('execute completed'); 
}

mainFunc();

Since I have await, I expected the output will be:

execute func1
execute func2
execute complete

But to my surprise, the output is

execute complete
execute func2
execute func1

I must have missed some important concept on this, any suggestion is highly welcomed.

react-draft-wysiwyg The converted base64 for image is overflowing from the upload image field

I have a working react-draft-wysiwyg editor application. I am able to add images to editor using this. There is one issue i am facing , please check this below :

Overflow of Base64 string with in the File Upload box

Here’s the code so far what i’ve tried. And note that for display purpose even if i pass truncatedUrl inside callback the error is “Invalid URL passed” ,

So basically what i am trying to do is show some small string inside the “File Upload” Box but when i click on “Add” the complete image URL needs to be passed.

Here’s what i’ve tried so far:

import {Editor} from "react-draft-wysiwyg";
import { EditorState, ContentState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

  const [editorState, setEditorState] = useState(EditorState.createEmpty())

 useEffect(() => {
    let html = stateToHTML(editorState.getCurrentContent())
    setContent(html)
  }, [editorState])

  const handleEditorChange = (state) => {
    setEditorState(state);
    const selectedBlock = state.getCurrentContent().getBlockForKey(
      state.getSelection().getStartKey()
    );
    const selectedEntity = selectedBlock.getEntityAt(
      state.getSelection().getStartOffset()
    );
    if (selectedEntity !== null) {
      if (typeof selectedEntity.getData === 'function') { // add this check
        const image = selectedEntity.getData().url;
        setImageFile(image); // remove data URL prefix
      } else {
        console.error('selectedEntity does not have getData method');
      }
    } else {
      setImageFile(null);
    }
  };


  const addLesson = async () => {
    setIsUploading(true);

    try {
      const formData = new FormData();
      formData.append('name', title);
      formData.append('content_type', contentType);
      if (contentType === 'text' && content) {
        formData.append('content', content);
      }
      if (contentType === 'video' && video) {
        formData.append('content', video);
      }
      formData.append('course_id', course_id);
      formData.append("imageFile", imageFile);

      const response = await axios.post(url() + 'api/admin/lessons', formData);
      if (response?.status === 200) {
        setSuccess('Lesson successfully added.');
        window.setTimeout(() => {
          history.push(`/course/${course_id}/lessons`);
        }, 1000);
      }
    } catch (error) {
      console.error(error);
      setError(error?.response?.data?.msg);
    }

    setIsUploading(false);
  };


return (

   <div className="row m-3">
                <h6 className="edit-box-label ml-2">Lesson Content</h6>
                <div className="col-xl-12">
                   <Editor
                     editorState={editorState}
                     onEditorStateChange={handleEditorChange}
                    toolbar={{
                      image: {
                        uploadCallback: (file) => {
                          return new Promise((resolve, reject) => {
                            const reader = new FileReader();
                            reader.readAsDataURL(file);
                            reader.onload = () => {
                              const dataURL = reader.result;
                              const truncatedDataURL = dataURL.substring(10, 30) + "..."; // set the maximum length of the truncated string
                              resolve({ data: { link: dataURL } , link : { url : truncatedDataURL} });
                            };
                            reader.onerror = (error) => {
                              reject(error);
                            };
                          });
                        },
                        alt: { present: true, mandatory: false }
                      }
                    }}
                   />
                </div>
              </div>
)

Requesting help regarding this , all your efforts are appreciated.

Regards,

Unable to stop parent event when I click an icon which display a tooltip

This is below HTML which has Anchor tag as parent most element. It has EM element, Onclicking this EM, I am displaying a Tooltip through scripting.

<a href="/content/sprint/sprint_com/us/en/shop/cell-phones/samsung-s20-fe-5g.html?"
  class="device-tile__link">
  <div class="device-tile device-tile-wall-card"> 
    <div class="font-size-12">
      + tax &amp; shipping
      <div>
        <em
          class="ico ico--info ico--md color--black js-tooltip-trigger"
          aria-describedby="dvc13090000prd"
          aria-hidden="true"></em>
        <div class="tooltip__content" id="dvc13090000prd">
            Tooltip Content
        </div>
      </div>
    </div>
  </div>
</a>

On clicking EM, The Tooltip is displaying and immediately it starts redirecting to other URL which Parent Anchor tag. I even try adding stopPropagation. It’s not working.

target.addEventListener('click', function(e) {
      if(e.target.tagName === 'EM') {
        e.stopPropagation();
        toogleTooltipMobilelistener;
      }
    }); 

How to use vue3 suspense with dynamically loaded components inside ?

I am trying to use Suspense component to show the loading state of dynamic components in my app. But here I come across the scenario where both keep-alive and Suspense require on single root node.

              <keep-alive>
                <Suspense>
                  <component
                    ref="stepForm"
                    :id="currentTabComponent.id"
                    :key="currentTabComponent.id"
                    :is="currentTabComponent.value"
                    @success="handleSuccess"
                  ></component>
                  <template #fallback>
                    Loading...
                    <img src="@/assets/images/auth-decoration.png" />
                  </template>
                </Suspense>
              </keep-alive>

However in the below code even if have only one root node inside of Suspense. It gives me this error.
[Vue warn]: <Suspense> slots expect a single root node.

I am doing exactly as said in the vue docs.
Is there any thing that I am missing? I am using Nuxt 3.2.3

How to update nested array value dynamiclly in react native

I am making dynamic UI, Getting response from backend and according to that making UI.
dynamicFormConfig is a object , inside there is 3 arrays , likes at 1st index
name: “Passport”, code: “passport”, visible: false, isSelected: false, property: Array(10)}

again inside there is property array whihc has some value .And in below code I am mapping
property array and making UI, this is one piece of code .
Now there will be multiple value in property as its dynamic , so I have to store the values dynamically .
So in below code “onChangeText” I was to update the field value which is inside the Property and then updated array I’ll store in redux

            dynamicFormConfig: {individualIdentification: Array(3)}
            
            dynamicFormConfig:
            individualIdentification: Array(3)
            0: {name: "Civil ID", code: "civilId", visible: true, isSelected: true, property: Array(1)}
            1: {name: "Passport", code: "passport", visible: false, isSelected: false, property: Array(10)}
            2: {name: "GCC", code: "GCC", visible: true, isSelected: false, property: Array(1)}
        
      1:
    code: "passport"
    isSelected: false
    name: "Passport"
    property: Array(10)
    0:
    errorMessage: {pattern: "Enter Alpha characters only", required: "First Name is Required"}
    id: "passportNumber"
    label: "ID"
    masterDataVal: ""
    maxLength: ""
    pattern: "^{0,8}"
    placeholder: "Enter Passport Number"
    required: true
    title: "Passport Number"
    type: "string"
    value: ""
    visible: true
            
            const {individualIdentification } = useSelector((state) => state.authUser.dynamicFormConfig);
              let dynamciPass= individualIdentification.filter(item=>item.code==="passport")  


{dynamciPass[0].property.map((item,index) => (
          <View>
            {item.type==='string' &&
        <View style={{ marginTop: 20 }}>
          <TextLight>{t(item.label)}</TextLight>
          <TextInput
            placeholder={t(item.placeholder)}
            onChangeText={(text) => {
              if (!/[^a-zA-Zs]/.test(text)) {
                // setFullName(text);
        // Here I want to update the value fields and then 
                //dispatch(passportDynamic({ key: item.label, value: text }));
                dispatch(setDynamicFormValueUpdate();
              }
            }}
            value={item.value}
            style={{
              borderBottomColor: colors.grey19,
              borderBottomWidth: 0.5,
              color: colors.textPrimary,
              borderStyle: 'dashed',
              ...RtlStyles.text,
            }}></TextInput>
        </View>}

Need help on js ASAP

I want to make the send buttons on the other selected files disabled when a file is sending and enable the send buttons when the file is sent.

Please give me a correct answer, I tried asking from chatgpt but not worked.

React onclick buttons returning empty strings 1 in 5 times

Im updating my state displayElement with a series of buttons.
I wanted to change the display on click using a button to reveal a new component.
It works but after a few clicks its stops working.
I start getting the return where normally and until a few seconds ago i get all the string names printed out nicely.

The error looks like this. With id of button clicked and name of Display component

 ID saves                OptionsNav.jsx:6
 Display saves           Design.jsx:15
 ID components           OptionsNav.jsx:6
 Display components      Design.jsx:15
 ID <empty string>       OptionsNav.jsx:6
 Display <empty string>  Design.jsx:15
 ID saves                OptionsNav.jsx:6
 Display saves           Design.jsx:15
 ID <empty string>

I cant figure out why the string would stop and how to code it better.
I cut all the code out that repeats itself.

 const [displayElement, setDisplayElement] = useState('nav');

 const setDisplay = (event) => {
  const { id } = event.target;
  console.log('ID', id);
  setDisplayElement(id);
 };

 <ul className='grid gap-2 grid-cols-3 lg:grid-cols-none mb-4 mt-2'>
  <li className='options__link' id='nav' onClick={setDisplay}>
    <button id='nav' onClick={setDisplay}>
      Nav
      </button>
    </li>
    <li className='options__link' id='palette' onClick={setDisplay}>
      <button id='palette' onClick={setDisplay}>
          Color
        </button>
      </li>

 <div className='border-2 border-solid border-black rounded'>
  {displayElement === 'nav' && <NavOptions />}
  {displayElement === 'palette' && <ColorPalette />}
  {displayElement === 'pages' && <PageOptions />}
  {displayElement === 'components' && <CompenentOptions />}
  {displayElement === 'footers' && <FooterOptions />}
  {displayElement === 'saves' && <SavedDesigns />}
</div>;

How to call function depending on onmessage from websocket?

so i have this project webpage with timer.
and i made websocket test server and connected to my project webpage(client).
i want the webpage’s timer to start&stop depending on message from server.
for instance, if server sends “12”, timer srats and if “24” timer to stop.

webSocket.onmessage = (event) => {
 alert(event.data);
 if (onmessage =12) {
start();
console.log('right');
}
if (onmessage =24) {
reset();
console.log('right2');
}

};

above is part of my websocket script. However, i can see the console.log, which means server&client is communicating well, but the function isn’t working :(.

i put websocket script in between my and . and timer&other js in the end of my html field as script src. if i put my websocket script in the same file as my other js, websocket won’t work. help please!

tried to put websocket in various location but won’t work.

Metamask not returning “code 4001 User rejected the request.” when closing login popup in Chrome, but works in Edge

I am trying to connect to the Metamask extension on Chrome by having a button that initiates the log in process on click. However in the event the user closes the log in pop up after clicking the button, no code 4001 exception is thrown in Chrome, the console log is completely empty. After that when I click the button again, it will no longer bring up the log in pop up but instead throw “RPC Error: Already processing eth_requestAccounts. Please wait.”
enter image description here

But when I tried in Edge, it throws just fine in the console (this is the expected result):
enter image description here

Refreshing the Chrome page does not help, I have to close and reopen the entire browser to reset it.

Looking into the extension icon, I noticed that in Edge, whenever I close the login button, the blue “1” notification which signifies pending transactions will be gone:

enter image description here

However in Chrome that is not the case, the blue “1” notification remains:

enter image description here

Here is the relevant code for the button if it helps. Any assistance is greatly appreciated:

import { Card, CardContent, Button, Grid } from '@material-ui/core'
import React, { useEffect, useState } from "react";
import MetaMaskOnboarding from '@metamask/onboarding';

function MetaMaskConnectButton(props) {    
    const forwarderOrigin = 'http://localhost:3000';    
    const onboarding = new MetaMaskOnboarding({ forwarderOrigin });    
    const { ethereum } = window;    
    const [buttonText, setButtonText] = useState('Connect MetaMask')    
    const [isButtonDisabled, setIsButtonDisabled] = useState(false)    
    const [mmAccounts, setMmAccounts] = useState('')    

    useEffect(() => {        
        if (!isMetaMaskInstalled()) {            
            setButtonText('Click here to install MetaMask!')        
        }
    }, [])    

    useEffect(() => {        
        if (mmAccounts == null || mmAccounts.length === 0)
            setIsButtonDisabled(false)       
        else            
            setIsButtonDisabled(true)    
    }, [mmAccounts])    

    async function metaMaskClientCheck() {        
        if (!isMetaMaskInstalled()) {            
            await metamaskInstall()            
            setIsButtonDisabled(true)        
        } 
        else {            
            await metamaskConnect()            
            setIsButtonDisabled(false)        
        }    
    }    

    //Function checks if the MetaMask extension is installed    
    const isMetaMaskInstalled = () => {        
        //Have to check the ethereum binding on the window object to see if it's installed          return Boolean(ethereum && ethereum.isMetaMask);    
    }    

    const metamaskInstall = async () => {        
        setButtonText('Onboarding in progress...')        
        setIsButtonDisabled(true)        
        onboarding.startOnboarding();    
    }    

    const metamaskConnect = async () => {        
        setIsButtonDisabled(true)        
        setButtonText('Connecting to MetaMask...')        
        try {            
            // Will open the MetaMask UI            
            let accounts = await ethereum.request({ method: 'eth_requestAccounts' }) 
            console.log('Ethereum Request over')            
            let account = accounts[0]            
            setMmAccounts(account)            
            setButtonText('MetaMask Connected')        
        } catch (error) {            
            console.error(error);            
            setIsButtonDisabled(false)            
            setButtonText('Connect MetaMask')        
        }    
    };    

    return (        
        <Grid container xs={12} sm={12}>
            <Grid container xs={6} sm={6} justify='flex-start'>
                <Button                    
                    disabled={isButtonDisabled}                    
                    variant='contained'                    
                    color='secondary'
                    className='button-blue originalText'
                    onClick={() => {
                        metaMaskClientCheck()
                    }}
                    classes={{ root: 'ng-button-filled-secondary' }}
                >
                    {buttonText}
                </Button>
            </Grid>
        </Grid>
    )}
export default MetaMaskConnectButton

How to transform a COUNT COLOR macro into a TypeScript code for excel online?

Como transformar una macro CONTAR COLOR en un código TypeScript para excel online?

Ingles
I am trying to transform the following macro to execute a CountColor function and I cannot eliminate the errors when loading it as a Script in excel online. If someone can guide me, I would appreciate it.

Español
estoy tratando de transformar la siguiente macro para ejecutar una funcion ContarColor y no logro eliminar los errores al cargarlo como Script en excel online. Si alguien me pueda guiar, se lo agradesco.

Codigo

> Function CONTARCOLOR(celdaOrigen As range, rango As range)
>  Application.Volatile
> 
>  'Variables
>  Dim celda As range
> 
>  'Recorremos todas las celdas del rango
>  For Each celda In rango
> 
>  'Compara la propiedad Interior.Color
>  If celda.Interior.Color = celdaOrigen.Interior.Color Then
>  CONTARCOLOR = CONTARCOLOR + 1
> End If
> 

Next celda
End Function

Esta función se llama con la siguiente formula:

=CONTARCOLOR(RANGO; Celda Referencia)

This script works but with a fixed range, I need to call it with a formula
este scrip funciona pero con un rango fijo, yo necesito llamarlo con una formula

> async function main(workbook: ExcelScript.Workbook) {
> let MiHoja = workbook.getWorksheet("Hoja1");
> let MiRango = MiHoja.getRange("E6:L30");
> let Fin = MiRango.getRowCount();
> let Final = MiRango.getColumnCount();
 
>    //capturamos formato del color de la celda B4
> let MiColor = MiHoja.getRange("B4").getFormat().getFill().getColor();
>     //creamos contadores
> let nItem = 0;
> Obtener los valores de cada celda en el rango
> let valores = MiRango.getValues();
> Iterar a través de los valores y colores de fondo de cada celda
>   for (let i = 0; i < Fin; i++) {
 
> for (let j = 0; j < Final; j++) {
> let valor = valores[i][j];
> let celda = MiRango.getCell(i, j);
> let colorFondo = celda.getFormat().getFill().getColor();
> Si el color de fondo es igual al de la celda de referencia, aumentar el contador
> if (colorFondo == MiColor) {
> nItem = nItem + 1
>             }
>         }
>     }
>     //Pasamos el resultado a la celda B3
> MiHoja.getCell(2, 1).setValues([
> [nItem]
>     ])
> }


Change the rendering order of input from a user and chatbot reply

So, I have this chat bot where you could ask a question and the bot will analyze the question and reply to it accordingly. So, the user just needs to input text in the input bar the question he/she wants to ask, and when he/she clicks submit button or just hit enter, the question is pushed to the conversation array and the bot replies based on the question asked and also the reply of the bot is also added to the conversation array. then the conversation array is mapped so that all conversations are rendered in the chat page in a way similar to facebook messenger; the chat bot’s reply are in the left side of the chat page and the question a user asks are on the right side of the chat page.(this is done when mapping the conversation array, all chats on the odd index are questions asked by the user, and the conversation on the even index is that of the bot’s reply). However, the problem I am facing now is, if the user inputs text and submits it very fast and repeatedly, the order of the conversation array gets messed up(for example, if I input and hit submit/enter four times at a very fast speed, all my 4 conversations I typed are rendered as if it’s a conversation between me and the bot and once the bot has a reply for the first question I asked, it’s displayed after 4 consecutive texts of mine and it might be even displayed either on the right side of the chat page or the left side. How can I solve this problem in react web app? I tried using setTimeout, but it’s not working for me or I am using it not in a correct way?

here is few of the code:

const SendChat = (e) => {
    e.preventDefault();

    // add text to show on conversation
    dispatch(pushToChatConvArray({ user_conv: UserConversation }));
    // Send API Call
    // setTimeout(() => dispatch(botConvrse({ id: parseInt(sessionId), utt_user: userUtter })), 5000);
    dispatch(botConvrse({ id: parseInt(sessionId), user_conv: UserConversation }));

    setUserConversation("");
  };


<div>
<form onSubmit={SendChat}>
          <input
            autoFocus
            className="user-chat-form"
            placeholder="What's on your mind?"
            onChange={(e) => setUserConversation(e.target.value)}
            value={UserConversation}
          ></input>
          <IconButton type="submit">
            <SendIcon />
          </IconButton>
        </form>
</div>
// the this content is displayed on the chatpage
let content = chatList.map((item, idx) =>
    idx % 2 == 0 ? (
      <motion.div
        key={`chat ${idx}`}
      >
        <ChatContainer userOrBot={idx % 2 === 0 ? 0 : 1} conversation={item} />
      </motion.div>
    ) : (
      <motion.div
        key={`chat ${idx}`}
      >
        <ChatContainer userOrBot={idx % 2 === 0 ? 0 : 1} conversation={item} />
      </motion.div>
    )

I tried to explain the main problem and provided few of the base code for the problem

How to make a tower crane with three.js

about the model, it can be imported directly, but the animation i have no idea to implement it:The hook of the tower crane can be lifted up and down and translated left and right

how to The make animation by three.js : hook of the tower crane can be lifted up and down and translated left and right

UseReducer dispatch getting called twice

I have the following piece of code and the usereducer disptach method is getting called twice. I read up on this and removed the strict mode from index. Now the method is called and run properly but the UI is not getting rendered with the updated value. Can someone please help?

import React, { useReducer, useState } from "react";

import "../App.css";

const initialState = [
  { time: "17:00", slots: 3 },
  { time: "18:00", slots: 4 },
  { time: "19:00", slots: 2 },
  { time: "20:00", slots: 4 },
  { time: "21:00", slots: 3 },
  { time: "22:00", slots: 2 },
];

const reducer = (state, action) => {
  switch (action.type) {
    case "update": {
      let index = state.findIndex((x) => x.time === action.value);
      console.log(index);
      if (state[index].slots > 0) {
        state[index].slots -= 1;
      }
      console.log(state);
      return state;
    }
  }
};

function Reservations() {
 const [availableTimes, dispatch] = useReducer(reducer, initialState);

 const handleSubmit = (e) => {
 e.preventDefault();
    dispatch({ type: "update", value: time });
  };

   return (
 <>
 <label htmlFor="res-time">Choose time</label>
        <select
          id="res-time "
          value={time}
          onChange={(e) => setTime(e.target.value)}
        >
          {availableTimes.map((availableTime) => {
            return (
              <option key={availableTime.time} value={availableTime.time}>
                {availableTime.time} - {availableTime.slots} slots available
              </option>
            );
          })}
        </select>

</>
  );
}

export default Reservations;

In my index.js, I have removed the strictmode

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  // <React.StrictMode>
  <BrowserRouter>
    <App />
  </BrowserRouter>
  // </React.StrictMode>
);

How can I fix VS code not running my HTML files

I was working on the css for my code and accidentally ran it, which turned it into a JSON file. Now, whenever I try to run any of my HTML files a new tab is opened that says unable to connect to local host. I’ve also tried running previous projects and they will not run. I get a message about opening a JSON file instead. Is there a way I can fix this? I really need it fixed asap as I am working on a final project.

I’ve tried reinstalling VS code but that didn’t do anything.