Typescript generic modal

I am writing a modal component for my React application. I want the modal props to be generic and consist of two properties type and data. The type tells me what type the modal is, and the data property tells me what kind of data it takes. I want the data to be dependent on the type, so whenever I specify the type I immediately know what data it uses. In other words I want to specify the modal data using the modal type.

For example, I got the following modal type:

export enum ModalType {
  Payment = "payment",
  Alert = "alert",
}

I want the payment modal data to consist of the following properties:

export type ModalPaymentData = {
  id: string;
  value: number;
}

and the alert modal data to be just null

export type ModalAlertData = null;

Now I am trying to write the generic ModalObject<T> type which looks as follows:

export type ModalObject<T extends ModalType> = {
  type: T;
  data: ...;
};

and based on the type I want to specify that this modal uses the data connected to that type. I managed to do it without generics, something like that:

export type ModalPaymentObject = {
  type: ModalType.Payment;
  data: ModalPaymentData;
};

export type ModalAlertObject = {
  type: ModalType.Alert;
  data: ModalAlertData;
};

export type ModalObject = ModalPaymentObject | ModalAlertObject;

Is there any way to achieve this using generics? Maybe I could add the second type to my generic ModalObject type? I kinda managed to make it work this way

export type ModalObject<T extends ModalType, D> = {
  type: T;
  data: D;
};

const MObj: ModalObject<ModalType.AddProject, ModalData[ModalType.AddProject]> =
  {
    type: ModalType.AddProject,
    data: null,
  };

But it’s really redundant and it looks like the second generic type might be dependent on the first one.

Trigger click on scroll

I’m trying to simulate a click on the mobile menu toggle on scroll. The code I’m trying to use:

<script type="text/javascript">
    $(window).on("scroll", clickMenu);

    function clickMenu() {
        var wScroll = $(window).scrollTop();
        if (wScroll > 1) {
            $(".mobile_nav").trigger("click");
            $(window).off("scroll", clickMenu);
    }}
</script>

Is not working sadly (Uncaught TypeError: Cannot read properties of undefined (reading 'slice')).

What should I do to make it work?

Thanks!

jQuery problems with offset()

I ran into a problem when creating a scroll for headlines.

I looked at the element code, the code swears at the element “..offset().top”

$(function() {

    var header = $("header"),
        introH = $("#intro").innerHeight(),
        scrollOffset = $(window).scrollTop()

    // scroll
    checkScroll(scrollOffset)

    $(window).on("scroll", function() {
        scrollOffset = $(this).scrollTop()
        checkScroll(scrollOffset)

    })


    function checkScroll() {

        if (scrollOffset >= introH) {
            header.addClass("fixed")
        } else {
            header.removeClass("fixed")
        }
    }

    // scroll keys
    $("[data-scroll]").on("click", function(event) {
        event.preventDefault();

        var
            blockId = $(this).data("scroll"),
            blockOffset = $(blockId).offset().top            /* This line */


        $("html, body").animate({
            scrollTop: blockOffset
        }, 500)
    })

})

enter image description here

TypeError: stream.setRawMode is not a function

I’m trying to get a single character user input as the following:

const readHandler = (inputHandler, stream = process.stdin) => {
    return new Promise(resolve => {
        stream.setRawMode(true);
        stream.setEncoding('utf8');

        const onResolve = result => {
            stream.off('readable', read);
            stream.setRawMode(false);
            resolve(result);
        }

        const read = () => {
            let input;
            while (input = stream.read()) {
                inputHandler(input, onResolve);
            }
        }

        stream.on('readable', read);
    });
}

But it throws me the Type error stream.setRawMode is not a function. I tried adding the if condition:

if (process.stdin.isTTY) {
    process.stdin.setRawMode(true);
}

but it did not fix.
node -p -e “Boolean(process.stdout.isTTY) also returns true.

.waitForXPath only works after mouse hover over element (rendered page)

I have the following Puppeteer code:

await pageSF.goto('SalesForcePage');
pageSF.waitForNavigation({waitUntil: 'networkidle2'});
await pageSF.waitForXPath("//span[@id='window' and text()='SFDC Admin']");

To find the following span in a Salesforce lightning page:

<span force-lookup_lookup="" data-proxy-id="aura-pos-lib-1" id="window">SFDC Admin</span>

I’ve been trying to figure out for hours why the selector doesn’t find anything, but then noticed that if I run puppeteer with {headless: false}, the selector finds the span if I hover over the span with the mouse cursor or interact with it manually in any way.

I’m pretty sure this has to do with how Salesforce Lightning renders the content on the pages, but how do I let the selector find the element without any manual intervention? Thanks in advance.

How to get only matched data in node.js using mongoose?

I am building a bus ticket booking app in node.js.
I want to fetch only related data about queries not all the data But I am getting all the data about Bus.

Here is the location model. only admin can enter data about locations.

const locationSchema = new mongoose.Schema(
  {
    departureLocation: {
      name: {
        type: String,
        required: true,
        lowercase: true
      },
      time: {
        type: String,
        required: true,
      },
      subLocations: { type: [String], lowercase: true },
    },
    arrivalLocation: {
      name: {
        type: String,
        required: true,
        lowercase: true
      },
      time: {
        type: String,
        required: true,
      },
      subLocations: { type: [String], lowercase: true },
    },
  },
  {
    timestamps: true,
  }
);

Here is the route table. Again admin…

const routeSchema = new mongoose.Schema({
  location:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Location',
    required: true
  },
  duration: {
    type: Number,
    required: true
  },
  date: {
    type:String,
    required: true
  },
},
{
  timestamps: true,
});

Bus model: Admin…

const busSchema = new mongoose.Schema({
    busNumber: {
      type: String,
      unique: true,
      required: true,
    },
    seats: {
      type: Number,
    },
    route: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Route",
      required: true,
    },
  },
  {
    timestamps: true,
  });

and here finally the booking table:

const bookingSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  busId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Bus",
    required: true,
  },
  passengers: [
    {
      name: { type: String, required: true, trim: true },
      gender: { type: String, required: true, trim: true },
      age: { type: Number, required: true, trim: true },
    }],
  phone: {
    type: Number,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  bookingDate: {
    type: String,
    required: true,
  },
  fare: {
    type: Number,
    required: true,
  },
  seats: {
    required: true,
    type: [Number],
  },
  departureDetails: [
    {
      city: { type: String, required: true, trim: true },
      location: { type: String, required: true, trim: true },
      time: { type: String, required: true, trim: true },
      date: { type: String, required: true, trim: true },
    },
  ],
  arrivalDetails: [
    {
      city: { type: String, required: true, trim: true },
      location: { type: String, required: true, trim: true },
      time: { type: String, required: true, trim: true },
      date: { type: String, required: true, trim: true },
    },
  ],
},{
    timestamps:true
});

Whenever an authorized user enters the booking data It is getting saved to the database. No problem whatsoever

Now I want to show every user(Non-authorized as well) of my app about trips(routes), the bus which will run on that particular trip and reserved and available seats in that particular bus which is currently stored.

But the problem is that I am getting all the buses even if it is not on that trip.

here is the query:

router.get("/trip/single", async (req, res) => {
  if (!req.query.departure || !req.query.arrival || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { departure, arrival, date } = req.query;
 
  let locations = await Location.find({
    'departureLocation.name': departure,
    'arrivalLocation.name': arrival,
  });
 
  const ids = locations.map(location => location._id)
 
  const routes = await Route.find({$and: [{location : {$in: ids}},{date}]});
  const route = routes.find(()=>{
    return ([{ date }, { routes }])
  });
 
  let buses = await Bus.find({})
  let matchedBuses = buses.filter((bus)=> {
    return bus.routes === locations._id
  })
  
  const bookings = await Booking.find({})
  const busIdWithSeatsObj = {}
  for(let i = 0; i < matchedBuses.length; i++){
    let currentBusSeats = []
    const busBookings = bookings.filter((booking) => {
      return (booking.departureDetails.date === date &&
        booking.busId.toString() === matchedBuses[i]._id.toString()
        )
    })
    busBookings.forEach((booking) => {
      currentBusSeats = [...currentBusSeats, ...booking.seats]
    })
    busIdWithSeatsObj[matchedBuses[i].seats] = currentBusSeats
  }
 
  res.status(200).send({route, matchedBuses, busIdWithSeatsObj});
});

Now I also want to fetch details by Id(only single bus).

How to do that?

Can anyone help me out here?

Settimeout in next js/react

let i = 0

function pollDOM() {     
  console.log(i)

  i++

  setTimeout(pollDOM, 3000) // try again in 300 milliseconds
}

pollDOM()

The above function use to run every 3 second, output is like:

1 

// wait 3 seconds

2 

// wait 3 seconds

3 

// wait 3 seconds

4 

// wait 3 seconds, and so on...

But in Next.js, it produces a result as:

1
2 

// wait for 3 seconds

3
4

// wait for 3 seconds

5
6

// wait for 3 seconds, and so on...

Why it is produced this way, two numbers together?

How can I achieve that that I am achieving in normal JavaScript?

How to pass params in Nuxt 3 server/api

I can’t figure it out how to pass params to an anonymous function in Nuxt 3.

index.vue

<template>
  <form @submit.prevent="signUpNewsletter()">
    <input type="email" placeholder="[email protected]" v-model="userEmail">
    <input type="submit" value="Submit">
  </form>
</template>

<script setup>
const userEmail = ref('[email protected]')

function signUpNewsletter () {
  useAsyncData(
    'newsletter',
    () => $fetch('/api/sign_up_news', {
      method: 'POST', // Post method works
      body: {
        email: userEmail.value
      }
    })
  )
}
</script>

server/api/sign_up_news.js

import { createClient } from '@supabase/supabase-js'

export default async (email) => { // can't read the parameter
  const SUPABASE_KEY = 'key123'
  const SUPABASE_URL = 'url.supabase.co'
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)

  const { data, error } = await supabase
    .from('newsletter')
    .insert([{ email }]) // <<< Fails!
  return data
};

working:

import { createClient } from '@supabase/supabase-js'

export default async () => {
  const SUPABASE_KEY = 'key123'
  const SUPABASE_URL = 'url.supabase.co'
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)

  const { data, error } = await supabase
    .from('newsletter')
    .insert([{ email: '[email protected]' }]) // <<< Works!
  return data
};

Do you know how to pass parameter into Nuxt 3 server/api? Or do you got a source? The docs official docs are blank at this moment.

setInterval stops working after 4 intervals

Description: setInterval will stop working after about 4-5 intervals and when it does do the interval it does them 1 second at a time (as if the page was tabbed and yes I tried f11). I placed breakpoints and it seems to just stop working.

here is the html used:

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        body{
            background-color: gray;
        }
    </style>

    <title>Document</title>
    <script defer src="test.js"></script>
</head>
<body>

<div id= "wrapper" class ="wrapper">
    <canvas  id="canvas" width="1920" height="1080" draggable="true"></canvas>
</div>


    <input placeholder="message">
    <button id="send">Send</button>
    
</body>
</html>

Here is the test.js used:

setTimeout(function () {
    console.log(1);
},1000/24);

Notes(likely to be edited): The rest of my script is irrelevant seeing as it still does not work with the given code. I have tried to simplify it to eliminate as many issues as possible. I am also serving this page static using express.

I had this working at one point but I do not know why it doesn’t work now, it’s likely something very subtle.

How can I blur only the background behind popup?

I implemented a popup that appears when a button is pressed, and want the background to be blurred when the popup message is on the screen. I’ve added a function called toggle() which activates/deactivates when clicking on the button:

function toggle() {
  var blur = document.getElementById('blur');
  blur.classList.toggle("active");
  var popup = document.getElementById('popup');
  popup.classList.toggle("active");
  var popup2 = document.getElementById('popup2');
  popup2.classList.toggle("active");
} 

And these are the CSS attributes I’ve added:

.container#blur.active {
  filter: blur(10px);
  pointer-events: none;
  user-select: none;
}

#popup.active, #popup2.active {
  pointer-events: all;
  filter: none;
}

.display-popup {
  visibility: visible;
  top: 50%;
  transform: translate(-50%, -50%) scale(1);
  filter: blur(0px);
}

where container is the whole website screen and popup and popup2 are two different popups. Right now, when the button is clicked, the whole website is blurred including the popup message.

I’d appreciate any help 🙂
(I’m using JavaScript)

Can’t use react state inside a socketio on event callback function

I am trying to make a component where when you add a task, an event listener gets added to the socketio client. The event gets triggered when the server reports the progress of the task and I want to update the task with the new progress.

The problem is that when I update the task progress, the event callback function uses the state of the component when the function got assigned. If the “tasks” state was empty prior to assignment, the progress update erases the state.

I don’t know how I can use the current state inside the callback function. (The progress update does work outside of the event callback)

Here is a minimal reproducible example:

import React, {useEffect, useRef, useState} from "react";
import axios from "axios";
import socketIOClient from "socket.io-client"


export default function TestComponent() {
    const socketRef = useRef(null);
    const [tasks, setTasks] = useState([])  // task: {id, name, time_start, progress}

    useEffect(() => {
        if (socketRef.current == null) {
            socketRef.current = socketIOClient({path: "/api/socket.io"});
        }

        return () => {
            socketRef.current.disconnect();
        };
    }, []);

    function addTask(task) {
        setTasks([...tasks, task]);
        addTaskProgressEvent(task);
    }

    function addTaskProgressEvent(task) {
        const event = "task:" + task.id + ":progress";

        socketRef.current.on(event, (progress) => {
            // update task progress (this failes!)
            setTasks(tasks.map(list_task => list_task.id === task.id ?
                {...list_task, progress: progress} : list_task))

            console.log(progress);
        })
    }

    function handleStartTask() {
        axios.post("/api/task").then((response) => {
            addTask(response.data);
        });
    }

    return (
        <div className="TestComponent">
            <button onClick={handleStartTask}>
                start task
            </button>
        </div>
    );
}

How can I turn the incrementing id of an element to a string without breaking react-beautiful-dnd

I’m making a Trello-like board (drag and drop board) and I’ve run into an issue. Currently for generating id’s I’ve been using v4(). I need to generate an incrementing id for every item added to a list. I have three lists: todo, inProgress and done. The problem is it has to be a string in order for dnd to work.

Here is what my addItem function looks like currently:

const addItem = () => {
    if (status === 'todo') {
      setList((prev) => {
        return {
          ...prev,
          todo: {
            title: 'Todo',
            tasks: [
              ...prev.todo.tasks,
              {
                id: v4(),
                title: title,
                status: status,
                user: user,
                description: description,
              },
            ],
          },
        }
      })
    } else if (status === 'inProgress') {
      setList((prev) => {
        return {
          ...prev,
          inProgress: {
            title: 'In Progress',
            tasks: [
              ...prev.inProgress.tasks,
              {
                id: v4(),
                title: title,
                status: status,
                user: user,
                description: description,
              },
            ],
          },
        }
      })
    } else {
      setList((prev) => {
        return {
          ...prev,
          done: {
            title: 'Done',
            tasks: [
              ...prev.done.tasks,
              {
                id: v4(),
                title: title,
                status: status,
                user: user,
                description: description,
              },
            ],
          },
        }
      })
    }
    setTitle('')
    setStatus('')
    setUser('')
    setDescription('')
  }

I’ve tried (list.length+1).toString() and it returns NaN.

Short circuit evaluation for OR and AND

I am researching a lot but could not find a valid answer.

I just want to know how the below code works when short ciruit happens

function check(val){
    console.log(val);
    return val;
}
if(check(0) && check(1) || check(3)){
    console.log("true")
}else{
    console.log("false")
}

Here the output is:

0
3
true

In my opinion , this is how short circuit work:
As && has higher precedence so the code will look something like this:

((check(0) && (check(1)) || check(3))

First check(0) is called and evaluated to false then the check(1) is not evaluated . After that the || check(3) gets called and evaluated.

But Here is the confusion:

if(check(3) || (check(0) && check(1))){console.log("true")}

In my opinion first , the (check(0) && check(1)) is evaluated due to higher precedence of && , but that’s not the case .
|| is executed first . Why?

Here the output would be:

3
true

Why (check(0) && check(1)) is not evaluated as they have high precedence