Is there option to have two month on air-datepicker?

I’m trying to setup the air-datepicker for two month view on desktop and one month view on mobile but it’s not succeeded, any recommendation how to achieve that?

Missing the next month, October for example

       // Initialize the Datepicker only once
    if (!pickerInitialized) {
        picker = new AirDatepicker('#datepicker-input', {
            inline: true,  // Display inline
            range: true,   // Enable range selection
            multipleDatesSeparator: ' - ', // Separator for date range
            showOtherMonths: true,  // Show adjacent month days
            numberOfMonths: 2,  // Show two months at the same time
            locale: englishLocale, // Set to English locale explicitly
            minDate: new Date(), // Disable past dates,
            onSelect({date, formattedDate}) {
                // Get the start and end date of the range
                selectedStartDate = date[0];
                selectedEndDate = date[1];

Deployed React App Returns “undefined” is Not Valid JSON Error on Campaign and Login

Title: Error “undefined” is not valid JSON in Production for React App

I recently deployed my React application at https://fundingfriends-frontend.onrender.com/. However, when I click on a campaign (for example, the first one), I encounter the following error:

react-dom.production.min.js:188 
SyntaxError: "undefined" is not valid JSON
    at JSON.parse (<anonymous>)
    at useToken.js:6:32
    ...

Similarly, when I try to log in, I get the same error:

react-dom.production.min.js:188 
SyntaxError: "undefined" is not valid JSON
    at JSON.parse (<anonymous>)
    at useToken.js:6:32
    ...

This is my first time deploying on Render, and my backend seems to be working fine. I can access the following API endpoints without any issues:

Relevant Code

useToken.js:

import { useState } from "react";

export default function useToken() {
    function getToken() {
        const tokenString = localStorage.getItem('accessToken');
        const userToken = JSON.parse(tokenString);
        if(userToken) {
            console.log("Found userToken");
            return userToken;
        } else {
            return null;
        }
    }

    const [token, setToken] = useState(getToken());

    function saveToken(userToken) {
        localStorage.setItem('accessToken', JSON.stringify(userToken));
        setToken(userToken);
    }

    return {
        token, setToken: saveToken
    }
}

Component Where Error Occurs (CampaignDetails.js):

import { useState, useEffect, useContext } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
import useToken from 'src/hooks/useToken';
import { APIURLContext } from 'src/contexts/APIURLContext';
import 'src/pages/CampaignDetails/CampaignDetails.css';

function CampaignDetail() {
  const { id } = useParams();
  const [campaign, setCampaign] = useState({ campaign: {}, donations: [] });
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const { token } = useToken();
  const apiURL = useContext(APIURLContext);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const campaignResponse = await axios.get(`${apiURL}/campaigns/${id}`);
        setCampaign(campaignResponse.data);
      } catch (error) {
        console.error("Error fetching campaign data:", error);
      }
    };

    fetchData();
  }, [id, apiURL]);

  useEffect(() => {
    setIsLoggedIn(!!token);
  }, [token]);

  const totalDonations = campaign.donations.reduce((total, donation) => total + donation.amount, 0);
  const progress = (totalDonations / campaign.campaign.goal) * 100;

  const handleEmailShare = () => {
    const subject = 'Check out this donation campaign!';
    const body = `Hi there,nnI found this donation campaign that I think you might be interested in. nnHere's the link: ${window.location.href}nnBest regards,n[Your Name]`;
    window.location.href = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  const handleSmsShare = () => {
    const message = `Check out this donation campaign: ${window.location.href}`;
    window.location.href = `sms:?body=${encodeURIComponent(message)}`;
  };

  return (
    <div className="details-page-container">
      <div className="row">
        <div className="col-md-6 d-flex flex-column justify-content-between">
          <div>
            <h1>{campaign.campaign.name}</h1>
            <p>{campaign.campaign.description}</p>
            <p>
              <span className="donation-amount">${totalDonations} </span>
              raised of ${campaign.campaign.goal}
            </p>
            <p>{campaign.donations.length} donations</p>
            <p className={`funded-status ${progress >= 100 ? 'funded' : ''}`}>
              {`This campaign is ${progress.toFixed(2)}% funded!`}
              <div className="progress">
                <div className="progress-bar" role="progressbar" style={{ width: `${(totalDonations / campaign.campaign.goal) * 100}%` }} aria-valuenow={(totalDonations / campaign.campaign.goal) * 100} aria-valuemin="0" aria-valuemax="100"></div>
              </div>
            </p>
          </div>
          <div className="mt-3">
            {isLoggedIn && (
              <form action={`${apiURL}/donations/create_checkout`} method='POST'>
                <input type='hidden' name='campaign_id' value={campaign.campaign._id} />
                <input type='hidden' name='campaign_name' value={campaign.campaign.name} />
                <input
                  type='number'
                  id='donation_amount'
                  name='donation_amount'
                  min='0'
                  step='0.01'
                  defaultValue='30.00'
                />
                {token && <input type='hidden' name='token' value={token} />}
                <button type='submit' className="donate-button">Donate</button>
              </form>
            )}
            <button className="share-button" onClick={handleEmailShare}>Share via Email</button>
            <button className="share-button" onClick={handleSmsShare}>Share via SMS</button>
          </div>
        </div>
      </div>
      <div className="row mt-5">
        <div className="col">
          <h3>Donations</h3>
          <div className="donations-container">
            {campaign.donations.map((donation, index) => (
              <div key={index} className="donation-card">
                <p><strong>Amount:</strong> ${donation.amount}</p>
                {donation.payment_id && <p><strong>Payment ID:</strong> {donation.payment_id}</p>}
                <p><strong>Message:</strong> {donation.message}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

export default CampaignDetail;

Question

Why am I getting the “undefined is not valid JSON” error in production but not in development? What steps can I take to debug this issue effectively?

Issues with ESM and CJS module resolution in my TypeScript package

I have developed a JavaScript scoped package named @rushipatange/calculate-it using TypeScript and Rollup, and I want to support both CommonJS (CJS) and ECModule (ESM) formats. I’ve transpiled my code to both formats and set up my package.json accordingly, but I’m encountering an issue when trying to use the package in an ESM context with .js extensions and will work with .mjs extensions . You can find the code here.

My Setup:

  • Languages/Technologies: TypeScript, Rollup
  • Transpiler: Rollup for bundling
  • Target Formats: CJS and ESM

package.json configuration:

{
  "name": "@rushipatange/calculate-it",
  "version": "0.0.3",
  "license": "MIT",
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.mjs", // will not work with .js extensions
  "exports": {
    ".": {
      "import": "./dist/esm/index.mjs", // will not work with .js extensions
      "require": "./dist/cjs/index.js",
      "types": "./dist/esm/index.d.ts"
    }
  },
  "scripts": {
    "build": "rm -rf ./dist && rollup -c rollup.config.mjs"
  },
  "files": [
    "dist/*"
  ],
  "keywords": [
    "calci",
    "calculator"
  ],
  "devDependencies": {
    "rollup": "^4.22.2",
    "rollup-plugin-commonjs": "^10.1.0",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-typescript2": "^0.36.0",
    "typescript": "^5.6.2"
  },
  "publishConfig": {
    "access": "public"
  }
}

Rollup Configuration:

Here’s a simplified version of my Rollup config:

// rollup.config.js
import typescript from "rollup-plugin-typescript2";
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import { defineConfig } from "rollup";

// Common Rollup plugins
const commonPlugins = [commonjs(), resolve(), typescript()];

// ESM Configuration
const esmConfig = defineConfig({
  input: "src/index.ts",
  output: {
    dir: "dist/esm",
    format: "es",
    sourcemap: true,
    preserveModules: true,
    preserveModulesRoot: "src",
    entryFileNames: "[name].mjs", // will not work with .js
  },
  plugins: [...commonPlugins],
});

// CommonJS Configuration
const cjsConfig = defineConfig({
  input: "src/index.ts",
  output: {
    dir: "dist/cjs",
    format: "cjs",
    sourcemap: true,
    preserveModules: true,
    preserveModulesRoot: "src",
    entryFileNames: "[name].js",
  },
  plugins: [...commonPlugins],
});

export default [esmConfig, cjsConfig];

Issue:

When I try to import the package in an ESM context (e.g., in a .mjs file), it still redirects me to the CJS version. For example:

import { add } from '@rushipatange/calculate-it'; // This imports the CJS version

What I’ve Tried:

  1. Ensured that package.json correctly specifies both main and module.
  2. Ensured that package.json correctly specifies exports field
  3. Verified that the output files are being generated correctly.
  4. Tried with .mjs extenstion by changing esmConfig entryFileNames field (it works)

Questions:

  1. What could be causing the ESM import to resolve to the CJS version?
  2. Are there any additional settings or configurations I should be aware of to ensure proper ESM support?
  3. Why it works with .mjs file extensions and not with .js extensions ?
  4. How can I make it workable for both ESM and CJS without .mjs extenstion ?

Any help or guidance would be greatly appreciated!

Cannot save captured image from webcam laravel 11 when using HTTPS

i just working for a project called “automatic face attendance system” that will detect users face, show information about the user, and save the captured image to local server.

the process is like:
user scan using webcam -> system matching user scanned face using models -> get the userdata using json -> save the captured image to server using json.

the problem is, i’ve turned on SSL from laragon and use HTTPS to improve the performance of my project, and everything is work except the function that “save the captured image”
but, if i turn off the SSL and use HTTP only, the “save the captured image” is working properly, it will save the captured images to server storage.

here is the codes:
js:

async function saveImageToServer(imageBlob, label) {
    const formData = new FormData();
    formData.append("image", imageBlob, "capturedImg.png");
    formData.append("label", label);

    try {
        const response = await fetch("/api/saveImage", {
            method: "POST",
            headers: {
                "CSRF-TOKEN": csrfToken,
            },
            body: formData,
        });

        if (response.ok) {
            const data = await response.json();
            if (data.imageUrl) {
                displayImageOnCanvas(data.imageUrl);
                console.log("Image saved and displayed on canvas");
            } else {
                console.error("Response did not contain imageUrl:", data);
            }
        } else {
            const errorData = await response.json();
            console.error("Failed to save image:", errorData);
        }
    } catch (error) {
        console.error("Error saving image:", error);
    }
}

controller

 public function storeImage(Request $request)
    {
        if ($request->hasFile('image') && $request->input('label')) {
            $timestamp = getCurrentDate();
            Session::put('current_date', $timestamp);

            $image = $request->file('image');
            $kodePegawai = $request->input('label');

            // Ensure the upload directory exists
            $uploadDir = 'labels/' . $kodePegawai . '/capturedImg/';
            Storage::disk('public')->makeDirectory($uploadDir);

            $imageName = $kodePegawai . $timestamp . '.png';

            $path = $image->storeAs($uploadDir, $imageName, 'public');

            if ($path) {
                $imageUrl = asset('storage/' . $uploadDir . $imageName);
                return response()->json(['imageUrl' => $imageUrl]);
            } else {
                return response()->json(['error' => 'Backend failed to save image'], 500);
            }
        } else {
            return response()->json(['error' => 'No image or label received'], 400);
        }
    }

result:

POST https://indodacin.test/api/saveImage 419
saveImageToServer @ script.js:261
(anonymous) @ script.js:197
setInterval
startFaceDetection @ script.js:142
await in startFaceDetection
(anonymous) @ script.js:59Understand this error
script.js:282 Error saving image: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

ive tried many solution from others thread, ask GPT what’s wrong. and all of their solution doesnt work.
here is what ive tried:

  1. check and update storage permission
  2. validating csrf token
  3. use path that have been specified on the server storage, etc

React not rerendering component parent based on change in state of child and parent

I am using react-redux toolkit and have state as object stored in redux store. On action dispatch I can see that the target key object and its parent are changed in the redux store (from redux dev tools)

But react doesnt rerender the target component and its parent too.
redux toolkit uses immer so I am assuming mutating fields in the object will trigger state change


import { createSelector, createSlice } from '@reduxjs/toolkit'
import { current } from '@reduxjs/toolkit';

const fooSlice = createSlice({
    name: "foo",
    initialState : {},
    reducers: {
       updateStatus(state, action) {
           const {tid, newStatus } = action.payload;
          const targetNode = state[tid];
          targetNode.status = newStatus;
          const parent = targetNode.pid;
          targetNode.status = newStatus;
       },
       setData(state, action) {
          return {...state, ...action.payload};
       }

   }
});


export const selectNode = (state, nodeId) => {
    return state.foo[nodeId] };

export const selectStatus = createSelector( [selectNode],
  (node) => {
    return node ? node.status : null}
);

In the component 

const nodeStatus = selectStatus(state, node.id);

function onChangeHandler(event) {    
        
        dispatch(updateStatus({tid: node.id, newStatus: event.target.value}));     
    }
<span>{nodeStatus}</span>


// in useEffect
//dispatch from api data to update initial state
dispatch( setData({'a' : { 
pid: 'b', 'status': 'xxx'}, 'b': {'status': 'xxx'}, 'c': {}}))


    

}


Echarts.drawChart happened Error in mounted hook

Echarts.drawChart happened Error in mounted hook: “TypeError: Cannot read properties of null (reading ‘getWidth’)”

I remember that it was able to run at first, but it couldn’t run last night. Today, it was the same problem when I pulled it out alone. This should be an error reported by the get width function called by echarts itself.

Wǒ jìdé zuì kāishǐ shì kěyǐ yùnxíng de, dàn zài zuótiān wǎnshàng jiù run bù qǐláile, jīntiān ba tā dāndú lā chūlái yěshì yīyàng de wèntí, zhège yīnggāi shì echarts zìjǐ qù diàoyòng de get width hánshù bào de cuòwù

used vue 2 and element-ui

Error line

Occur line

This is code


<!DOCTYPE html>
<html lang="en" xmlns="">
    <head>
        <meta charset="UTF-8">
        <title>title</title>
        <script src="./js/vue.js"></script>
        <link rel="stylesheet" href="./css/element-ui.css" />
        <script src="./js/element-ui.js"></script>
        <script src="./js/host_config.js"></script>
        <script src="./js/echarts.js"></script>
        <script src="./js/axios.js"></script>
    </head>
    <body>
        <div class="index" id="index">
            <div style="display: flex;">
                <div style="width: 12%;min-width: 205px">
                    <el-row class="tac unSelected">
                        <el-col :span="12">
                            <el-menu :default-active="activeIndex" class="el-menu-vertical-demo">
                                
                            </el-menu>
                        </el-col>
                    </el-row>
                </div>
                <div style="width: 87%; min-width: 1200px">
                    <div>
                        <el-card class="box-card unSelected">
                            <div style="width: 100%;height: 300px" ref="top-count">
                                
                            </div>
                        </el-card>
                    </div>
                    <div style="display: flex;flex-direction: row;margin-top: 15px;font-weight: bold" class="unSelected">
                        <el-card class="" style="width: 80%">
                            <div ref="main" style="width: 100%;height: 200px">
                                
                            </div>
                        </el-card>
                        <el-card class="monitor-card">
                        </el-card>
                    </div>
                </div>
            </div>
        </div>
    </body>

    <script>
        let vm = new Vue({
            el: "#index",
            data() {
                return {
                    isLoading: false,
                    refreshIcon: "el-icon-refresh",
                    icon: ['el-icon-refresh', 'el-icon-loading'],
                    counted: {},
                    result: [],
                    activeIndex: '1',
                    graph_data: [],
                    graph_date: [],
                    api_name: [],
                    api_count: [],
                    line_name: ['总数', '成功数', '失败数'],
                    count: [],
                    servers: []
                };
            },
            methods: {
                loadData() {
                    axios.get(window.RT_ENV.host_config.host + "/api/statistics").then(res => {
                        this.result = res.data.data[1]
                        let apiCount = res.data.data[2]
                        this.overview[0].data = res.data.data[0].total
                        this.overview[1].data = res.data.data[0].success
                        this.overview[2].data = res.data.data[0].failed
                        this.overview[3].data = res.data.data[0].successRate
                        let sort = [{}, {}, {}, {"2": "1"}, {}]
                        this.result.forEach(i => {
                            if (i.date === "今天") {
                                sort[0] = i;
                            } else if (i.date === "昨天") {
                                sort[1] = i;
                            } else if (i.date === "前天") {
                                sort[2] = i;
                            } else {
                                if (sort[3]["2"] === "1") {
                                    sort[3] = i
                                } else {
                                    sort[4] = i
                                }
                            }
                        })
                        const totalArray1 = [];
                        const successArray1 = [];
                        const failed1 = [];
                        const time = [];
                        apiCount.forEach(item => {
                            this.api_name.push(item.name)
                            totalArray1.push(item.total);
                            successArray1.push(item.success);
                            failed1.push(item.failed)
                            time.push(item.time)
                        })
                        this.api_count.push(totalArray1, successArray1, failed1, time)
                        const totalArray = [];
                        const successArray = [];
                        const failed = [];
                        sort.forEach(item => {
                            this.graph_date.push(item.date)
                            totalArray.push(item.total);
                            successArray.push(item.success);
                            failed.push(item.failed)
                        });
                        this.graph_data.push(totalArray, successArray, failed)
                        this.drawChart();
                        this.refreshIcon = this.icon[0]
                        this.isLoading = false
                        this.$loading().close()
                    }).catch(e => {
                        this.isLoading = false
                        this.$loading().close()
                        e.toString()
                    })
                },
                drawChart() {
                    let myChart = echarts.init(this.$refs['main'])
                    let top = echarts.init(this.$refs['top-count']);
                    let option1 = {
                        title: {
                            text: '调用详情'
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {type: 'shadow'}
                        },
                        legend: {},
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'value',
                            boundaryGap: [0, 0.01]
                        },
                        yAxis: {
                            type: 'category',
                            data: this.api_name
                        },
                        series: [{
                                name: '成功数',
                                type: 'bar',
                                data: this.api_count[1]
                            },
                            {
                                name: '失败数',
                                type: 'bar',
                                data: this.api_count[2]
                            },
                            {
                                name: '总调用数',
                                type: 'bar',
                                data: this.api_count[0]
                            },
                            {
                                name: '平均耗时',
                                type: 'bar',
                                data: this.api_count[3]
                            }
                        ]
                    };

                    let option = {
                        xAxis: {
                            type: 'category',
                            data: this.graph_date
                        },
                        yAxis: {
                            type: 'value'
                        },
                        title: {
                            text: '调用趋势图'
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: this.line_name //header
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: false,
                            }
                        },
                        series: [{
                                name: this.line_name[0],
                                type: 'line',
                                data: this.graph_data[0]
                            },
                            {
                                name: this.line_name[1],
                                type: 'line',
                                data: this.graph_data[1]
                            },
                            {
                                name: this.line_name[2],
                                type: 'line',
                                data: this.graph_data[2]
                            },
                        ]
                    };
                    top.setOption(option1)
                    myChart.setOption(option);
                },
                init() {
                    this.loadData()
                    this.drawChart()
                },
            },
            mounted() {
                this.init()
            },
        });
    </script>
    <style>
        .box-card {
            text-align: left;
            margin-top: 15px;
        }

        .monitor-card {
            text-align: left;
            margin-left: 15px;
            width: 20%;
        }

        .count-card {
            text-align: left;
        }

        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .top-content {
            overflow: hidden;
            padding: 5px;
            font-size: 14px;
            font-weight: bold;
            color: rgba(2, 2, 2, 0.6);
            display: inline-block;
            white-space: nowrap;
            text-overflow: ellipsis;
            max-width: 150px;
            //width: 50px;
        }

        .top-title {
            font-size: 16px;
            font-weight: bold;
            color: rgba(2, 2, 2, 0.7);
            max-width: 150px;
        }

        .unSelected {
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        .dividing-lines {
            border: rgba(2, 2, 2, 0.05) 1px solid;
            margin: 0 20px 0 20px;
        }

        .red {
            color: red;
        }

        .green {
            color: green;
        }

        .text-t {
            font-size: 14px;
        }

        .item-t {
            padding: 25px 0;
            font-size: 17px;
        }

        .box-card-t {
            margin-left: 2%;
            color: #ffffff;
            margin-right: 2%;
            width: 250px;
            cursor: pointer;
            border-radius: 15px !important;
        }

        .el-menu-item {
            width: 200px !important;
            height: 100%;
        }

        .el-col-12 {
            width: 100% !important;

        }

        .tac {}

        .el-menu {
            background: none;
        }
    </style>
</html>

host_config.js

!function () {
    window.RT_ENV = {
        host_config: {
            host: 'https://47.109.110.245:443/apis'
        }
    }
}()

No way found, Please give me some advice!

SSR shows signedIn state as false after page reload despite existing session cookie

The signedIn state is shown as false on the server-side after a page reload, even though the session cookie exists and the client correctly shows it as true. When I first sign in, I can see the cookie is added in the browser, and also I see it in the terminal and signedIn is set to true. After I reload the page, I still can see the cookie in both terminal and the browser, but now I also see:
*ssr* signedIn: false
signedIn: true

which probably indicates that signedIn state on server does not match state on client after page reload, although the response is successful and the cookie persists. Also, after page reload I can see multiple hydration issues occur in the console and my header ‘sign out’ button and ‘profile’ link are messed up, because now ‘sign in’ link appeared as well.

Video of the issue: https://www.veed.io/view/4a6216e4-6316-4cd3-8829-08034de3a1fe?panel=share. Here I’m signed in and I reload the page, the issue occurs, I can see both profile, sign out and sign in in the DOM, and then I click sign out.

Function in the composable:

const checkSession = async () => {
    const { apiBase } = useRuntimeConfig().public;
    try {
        const res = await $fetch<{ signedIn: boolean }>(
            `${apiBase}/check-session`
        );
        state.signedIn = res.signedIn;
        console.log('signedIn: ', res.signedIn);
    } catch (err) {
        console.error('Error checking session: ', err);
    }
};

check-session.get.ts:

export default defineEventHandler(async event => {
    const sessionCookie = getCookie(event, 'session');
    if (sessionCookie) {
        console.log('cookie (server): ', sessionCookie);
        return { signedIn: true };
    }
    return { signedIn: false };
});

Header template:

<div v-if="!signedIn">
    <NuxtLink
        class="flex items-center gap-2"
        to="/sign-in">
        <span>Sign In</span>
    </NuxtLink>
</div>
<div
    class="flex items-center gap-10 lg-max:gap-4"
    v-else>
    <NuxtLink
        class="flex items-center gap-2"
        to="/profile">
        <span>Profile</span>
    </NuxtLink>
    <button
        class="flex items-center gap-2"
        @click="handleSignOut">
        <span>Sign Out</span>
    </button>
</div>

I suppose the issue might be related to the Nitro as it is in between the Vue front and API, but I’m not sure.

Looking for a possible solution. Let me know if you need more details.

a question about then handler of a promise with a setTimeout inside the promise

I have this piece of code:

var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    setTimeout(()=>{
      res(  console.log("done: " + num)  )
    }, 2000);
    console.log("Getting here???" + num);
  });
}


myPromise(myArray[0]).then(x =>  
    console.log("what value: " + x));


I am really confused as to why the console.log(“what value: ” + x) print x as undefined.

I have read an example here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#return_value especially the one it says under “Chaining”.

In that piece of code, the asynchornicity of “then” is demonstrated clearly I think because I can see that the console.log or something inside then “later then” get executed before the “then that comes before it”. So we were able to see the order of print out in the console like this:

// Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising
// foobar
// foobarbaz

but how comes in my code above, even thought the (“what value: ” + x) actually executed after the promise in front of it, it still gets an undefined for the variable x?

enter image description here

On the other hand, the code in the example from the javascript site is able to have those “later then” getting the string value passed from those “then” or “promise” before it?
but my code here is not able to get the x value coming from the promise that comes before it? (I am confused because the printout seems to suggests the code inside the then get executed after myPromise’s promise resolve. But x being undefined seems indicating something I don’t understand.

Could someone explains why x is undefined?

thanks a lot

I have read example from the mozilla site, and also example from here How to execute promises sequentially, passing the parameters from an array?

but that example seem not quite similar to what I have here.

How does javascript actually run code? noobie

I recently start learing js. I mainly work with python. js

I don’t understand why the first two event listeners didn’t call the eventListener function.

I removed the event listeners at the end of the code, so the code before the last line should have run, right?

Angular: click event for video

I am trying to bind click event on video but it is not working. I need to fire event whenever user click on anywhere on the video or controls of video element. I have tried following:

component.html

         <video
          [src]="url"
          (loadeddata)="onVideoLoaded($event)"
          (click)="doSomething($event)"
        >
        </video>

component.ts

   onVideoLoaded(event) {
    const videoEl = event.target as HTMLVideoElement;
    videoEl.onclick = (event) => this.doSomething(event)
    videoEl.addEventListener('mousedown', this.doSomething);
  }

  doSomething(event){
    console.log(event)
 }

None of the above approach to bind video click event is working. How can I do it?

Illustrator SDK: Run without launching Illustrator

Is it possible to use the Illustrator Javascript SDK without actually launching Illustrator itself? Or is there some kind of more lightweight non-visual engine that can be running instead of the full-blown app interface?

I’m looking to create some Javascript files to batch trace thousands of JPGs and to do it without all the bloat of Adobe Bridge. I’m hoping to run the javascript file via a command line rather than through Illustrator’s FILE->SCRIPT menu.

Plus, any time I try it with bridge it always crashes after a few hundred so I have to keep starting the process manually where it stopped multiple times. I was hoping to be able to maybe execute this file with arguments dynamically and remotely. The less useless visual stuff I have running on my desktop (or maybe even a server), the better.

Get object from s3 in Express JS server and send it as response

Upon an authorized request of a client, I want to send a file back a file as response. Here, I’m getting the file from S3 bucket. What is the approach to send back the file back from S3 and send it to client?

const s3 = new S3Client({...})

router.get('/getfile', (req, res) => {
  const data = await s3.send(
    new GetObjectCommand({
      Bucket: 'bucket',
      Key: 'path',
    })
  )

  // an efficient way to send back the file
  // res.send(fileStream)
})

How can I send back the data?

Uncaught TypeError: import_mongoose.default.connect is not a function | HONO | Typescript

I am trying to build an app using hono, I want to use mongoose but on running the server it shows service core:user:backend: Uncaught TypeError: import_mongoose.default.connect is not a function

import { Hono } from "hono";
import mongoose from "mongoose";
const app = new Hono();

app.get("/", (c) => {
  return c.text("Hello Hono!");
});
mongoose
  .connect(
    ""
  )
  .then(() => {
    console.log("Connected To DB");
  })
  .catch((error) => {
    console.log(error);
  });
export default app;

Help me with this

I tried installing @types/mongoose also but still the problem persists