vite + Vue.js 3: how to build with the final export value?

I have a large ts data file:

data.ts :

export data = [
  ... // huge data 
]

the lib.ts just use some of the data:

import { data } from './data.ts';

const fitteredData = data.splice(0,2) // only use some of them

export { fitteredData };

I use fitteredData in my vue component:

<script setup lang="ts">
import { fitteredData } from "./lib";
</script>

<template>
  <div>{{ fitteredData }}</div>
</template>

After run pnpm build, I find all of the data in data.ts are builded in final file. How to make the final file only with the fitteredData?

How to make the final file only with the fitteredData, to make the final builded files smaller.

Using bycrpt.compare in node.js app but it isn’t being called or working at all

I am using bycrypt for my login process and it doesn’t seem to be working. I have already stored the previously hashed password in the database so I am retrieving it from the database and then comparing it with the password but it is like my bycrpt.compare isn’t even being activated in my code. I have verified that my password and the hashed password are there, and they do work but still nothing.

Here is my code:

app.post("/login", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  const responseArr = [];
  let passwordStatus = "";

  db.query(
    "SELECT password FROM users WHERE username = $1",
    [username])
    .then((res) =>  {
      
        const hash = res.rows[0].password;
        console.log("hash", hash);
        console.log("password", password);



        bcrypt.compare(hash, password, function(err, result) {
          console.log("in func", res.rows[0].password)
          console.log("in func", password)
        
              if(result){
                  console.log("login success");
                  console.log(result);

                  passwordStatus = true;
                  

              }else{
                  console.log('login failed');
                  passwordStatus = false;
              }

              if (err) {
                console.log("err", err)
              }
          })
   
        console.log("passwordStatus", passwordStatus);
        return passwordStatus;
      })
    .then((result) => {
      if (result === true) {
        const userResponse = db.query(
          "SELECT user_id FROM users WHERE username = $1;",
          [username]
        );
        return userResponse;
      } else {
        res.status(404);
        console.log("result was false")
      }
    })
    .then((response) => {
      responseArr.push(response.rows);
      res.status(200).send(responseArr);
    })
    .catch((error) => {
      console.log("error:", error);
      if (error) {
        throw error;
      }
    });
});```

Tab key is always hiding the Datepicker (accessibility)

<input id="BirthDate.0" name="BirthDate.0" class="input-sm input_mask mask_date form-control hasDatepicker" onchange="updateFieldGrid('UpdateField', this)" style="" value="" type="text" aria-label="Birth Date" size="11" maxlength="10" placeholder="mm/dd/yyyy" autocomplete="off">

$('input[type="text"].hasDatepicker').keydown(function(event) {
    var target = $(event.target);
    if(event.keyCode == 9) {
        if(!target.datepicker("widget").is(":visible")) {
            target.datepicker("show");
        } else {
            target.datepicker("hide");
        }
    }
});

I have been asked to make a datepicker more accessible, IE a user navigates to the birth date field using the tab key, hits the tab key again, the datepicker opens and they are able to navigate the picker via keyboard buttons, they hit tab again and it closes the picker and focus shifts to the next form element.

The above code gets the datepicker to show when hitting the ‘tab’ key. However, if you hit tab twice to hide it from the same focused text input field target.datepicker("widget").is(":visible") still evaluates to false. It in fact always evaluates to false. If I check for a different keypress, say the ‘a’ key which has a keycode of 65 it will indeed hide the datepicker on the second keypress. I’ve tried event.preventDefault() but this still doesn’t resolve it.

For the life of me I am unable to debug why this is happening and why it is always hiding the datepicker whenever I press ‘tab’ and before the keydown event handler is activated. The debugger shows it being already closed when it enters the keypress handler despite it having been opened when I pressed the key, and this isn’t happening for most other keys. So my guess is somewhere upstream prior to the keydown handler being called it is hiding the datepicker, but where?

Edit:
I found the following snippet in the jquery-ui-1.13.2.min.js file:

    _doKeyDown: function(a) {
        var b, c = d.datepicker._getInst(a.target);
        b = !0;
        var f = c.dpDiv.is(".ui-datepicker-rtl");
        c._keyEvent = !0;
        if (d.datepicker._datepickerShowing)
            switch (a.keyCode) {
            case 9:
                d.datepicker._hideDatepicker();
                b = !1;
                break;

I set the breakpoint to the datepicker being hidden basically, and it is executing this code. It looks to be default datepicker functionality to hide the datepicker on tab keypress (keycode = 9). Any way to override this?

Updating Child Component State Based on Successful Execution of Parent Component’s Reducer Function

I am trying to update the Child component if the reducer function in Parent component runs successfully.

function reducer(state, action) {
  if (action.type === "something") {
    try {
        action.cb();
        return { ...state, updated: true };
    } catch (error) {
        action.cb(error)
    }
  }
}

function Parent() {
    const [state, dispatch] = useReducer(reducer)

    return <Child dispatch={dispatch}></Child>
}
function Child({ dispatch }) {
    const [state, setState] = useState(false)

    function handleClick () {
        function cb(err) {
            if (!err) {
                setState(true)
            } 
        }
        
        dispatch({ type: "something", cb: cb });
    }

    return <button onClick={handleClick}>Click me</button>;
}

But when I run the above code I get a warning

Warning: Cannot update a component (Child) while rendering a different component (Parent)

how can I update the Child component’s state if there is no error in the reducer function?

How to filter cities based on province selected in dropdown

I’m developing a web app feature where the City dropdown values should filter based on the selected Province. Currently, when you select either the Province or the City dropdown, it doesn’t filter at all.

Here’s what I’ve tried so far but it doesn’t work:

Header component (attempted filtering logic lives here):

export const Header = ({ data, isLoading, error }: HeaderProps) => {
  ...

  // Bring in global state
  const {
    provinceDropdownFilter,
    cityDropdownFilter,
  } = useFilterStore();

  const filteredData = data.map((group) => group.equipments).flat();

  ...

  const handleDropdownFilterProvince = (
    e: React.ChangeEvent<HTMLSelectElement>
  ) => {
    useFilterStore.setState({ provinceDropdownFilter: e.target.value });

    // Filter the data based on the selected province
    const filteredCities = filteredData
      .filter((item) => item.state === e.target.value)
      .map((item) => item.city);

    // Set the filtered city dropdown options
    useFilterStore.setState({ cityDropdownFilter: filteredCities });
  };

  ...

  return (
    <>
      ...
          <Dropdown
            data={data}
            value={provinceDropdownFilter}
            onChange={handleDropdownFilterProvince}
            filterType="state"
          />
          <Dropdown
            data={data}
            value={cityDropdownFilter}
            onChange={handleDropdownFilterCity}
            filterType="city"
          />
      ...
    </>
  );
};

Dropdown component:

export const Dropdown: React.FC<DropdownProps> = ({
  data,
  onChange,
  value,
  filterType,
}) => {
  ...

  const filteredData = data.map((group) => group.equipments).flat();

  // Filter the data based on the filterType
  const filteredOptions = filteredData.filter((i) => {
    if (filterType === "manufacturer") {
      return i.manufacturer;
    }
    if (filterType === "state") {
      return i.state;
    }
    if (filterType === "city") {
      return i.city;
    }

    return false;
  });

  ...

  return (
    <>
      <Select
        aria-label="Select"
        placeholder={getCustomPlaceholder(filterType) as string}
        value={value}
        onChange={handleFilters}
      >
        {Array.from(uniqueValues)
          .sort()
          .map((value) => (
            <option key={value} value={value}>
              {value}
            </option>
          ))}
      </Select>
    </>
  );
};

Zustand Store:

const useFilterStore = create<FilterState>(
  zukeeper((set: any) => ({
    ...
    provinceDropdownFilter: "",
    cityDropdownFilter: "",
    ...
    setProvinceDropdownFilter: (value: string) =>
      set({ provinceDropdownFilter: value }),
    setCityDropdownFilter: (value: string) =>
      set({ cityDropdownFilter: value }),
    ...
  }))
);

Vue.js and Canvas: Issue with Coordinate Mapping for Dynamic Dot Layouts

I am using vue & html-canvas try to write a responsive “link Game”, here is the sample
[![enter image description here][1]][1]

But I found a really strange problem, Because I want to check if the line is “legitimate” when user make a line between two dots.
here is the picture describe what is “legitimate”:
[![enter image description here][2]][2]
Group1(which is col-1 & col2) may link together.
Group2(which is col-1 & col2) may link together.

To archive this goal, I use a variable to record each dot’s information.
this.Dotlocation[[RowID,ColID,GroupID],[x_location,y_location]]

But I found that that is whatever I do the information never get correct. here is the result

[ 
 // id,col,group
 [ [ 3, 2, 4 ], [ 631.4, 417.43 ] ], 
 [ [ 3, 1, 3 ], [ 495, 417.43 ] ], 
 [ [ 2, 1, 3 ], [ 214, 495 ] ],
 [ [ 1, 1, 3 ], [ 990, 462 ] ],
 [ [ 1, 2, 4 ], [ 631.4, 184.6002 ] ],
 [ [ 1, 1, 3 ], [ 495, 184.6002 ] ],
 [ [ 0, 1, 3 ], [ 990, 171 ] ],
 [ [ 2, 2, 4 ], [ 631.4, 301 ] ],
 [ [ 2, 1, 3 ], [ 495, 301 ] ],
 [ [ 0, 2, 4 ], [ 631.4, 68.2 ] ],
 [ [ 0, 1, 3 ], [ 495, 68.2 ] ],
 [ [ 4, 2, 4 ], [ 631.4, 533.801 ] ],
 [ [ 4, 1, 3 ], [ 495, 533.801 ] ],
 [ [ 1, 1, 3 ], [ 214, 301 ] ],
 [ [ 0, 1, 3 ], [ 214, 107 ] ]
 ]

There are several questions in this array:

  1. I don’t know why id is disordered.
  2. The Group&col are incorrect; it seems like the last column’s problem

Here is my code ( I’m sorry it’s a little bit long):

DrawImgOnCanvas(question,context1){
    let Column_Amount=question.length;
    var onchangegroup = false;
    let Column_ID = 1
    this.Group = 1       
    for (let col = 0; col < question.length; col++) { //Column
        console.log("col",col);
        //紀錄錨點資訊
        // let Dot_Row_ID = 1
        const Max_Img_Size = this.CountMaxImgSize(this.QuestionDataStructure[col].length);
        let RWD_Colum_Gap=this.CountRWDYGap(question[col])
        
        console.log(RWD_Colum_Gap);

        for (let Dot_Row_ID = 0; Dot_Row_ID < question[col].length; Dot_Row_ID++) { //Row
            console.log("Group1",this.Group);
            let Img = new Image();
            // let Image_Url=new URL(`../../${question[col][row]}`, import.meta.url).href
            let Image_Url = icon //FIXME: change to dynamic import
            Img.src = Image_Url;

            let Img_Size = this.ResizeRWDImg(Max_Img_Size,Img);
            // Img.height = Img_Size.New_Height;
            // Img.width = Img_Size.New_Width;
            let x = this.Min_border + Max_Img_Size.Max_Width*col + this.RWD_Gap_Width*col
            let y = this.Min_border + RWD_Colum_Gap + Max_Img_Size.Max_Height*Dot_Row_ID
            // let bordr=100
            Img.onload = () => {
                console.log(this.Min_border);
                context1.drawImage(Img, x, y, Img_Size.New_Width, Img_Size.New_Height);
                context1.beginPath();
                if (col == 0) {
                    console.log("Add on Right: Using Group",this.Group);
                    // add on right
                    context1.arc((x+Img_Size.New_Width+this.Min_border), (y+(Img_Size.New_Height/2)), this.DotRadius, 0, Math.PI * 2, true);
                    this.DotLocation.push([[Dot_Row_ID,Column_ID,this.Group],[x+Img_Size.New_Width+this.Min_border, y+Img_Size.New_Height/2]]);
                    context1.fillStyle = 'black';
                    context1.fill();
                }
                else if (col == Column_Amount-1) {
                    // add on left
                    context1.arc(x-this.Min_border,(y+(Img_Size.New_Height/2)), this.DotRadius, 0, Math.PI * 2, true);
                    this.DotLocation.push([[Dot_Row_ID,Column_ID,this.Group],[x-this.Min_border, y+Img_Size.New_Height/2]]);
                    context1.fillStyle = 'black';
                    context1.fill();
                }
                else{
                    console.log("Add on Both: Using Group",this.Group);
                    //Right
                    context1.arc((x+Img_Size.New_Width+this.Min_border), (y+(Img_Size.New_Height/2)), this.DotRadius, 0, Math.PI * 2, true);
                    this.DotLocation.push([[Dot_Row_ID,Column_ID+1,this.Group+1],[x+Img_Size.New_Width+this.Min_border, y+Img_Size.New_Height/2]]);
                    //Left
                    context1.arc(x-this.Min_border,(y+(Img_Size.New_Height/2)), this.DotRadius, 0, Math.PI * 2, true);
                    this.DotLocation.push([[Dot_Row_ID,Column_ID,this.Group],[x-this.Min_border, y+Img_Size.New_Height/2]]);
                    context1.fillStyle = 'black';
                    context1.fill();                
                }
                context1.closePath();
            }
            // Row_ID++;
        }
        if (col != 0) {
            console.log("Change Group");
            this.Group++;
            Column_ID +2 ;
        }
    }
},

here is the input datas:

question:[  
['assets/GamePic/Cat.png','assets/GamePic/Cat.png','assets/GamePic/Cat.png'],
['assets/GamePic/Cat.png','assets/GamePic/Cat.png','assets/GamePic/Cat.png','assets/GamePic/Cat.png','assets/GamePic/Cat.png'],  
['assets/GamePic/Cat.png','assets/GamePic/Cat.png']
],

Thank you for your patient, hopes for your reply.

  [1]: https://i.stack.imgur.com/MmxjB.png
  [2]: https://i.stack.imgur.com/MoZX6.png

Rock Paper Scissors game – looking for guidance on adding rounds and DOM

Here’s my JS and HTML. I am wondering how I can add the playGame function to my playRound function so I can include rounds. Also, I want to display the winner of the game after 5 rounds without having to click one of my rock, paper, scissors buttons.

https://codepen.io/Reginald86/pen/GRLjpYZ

const rock = document.querySelector("#rock").addEventListener("click", function () {
let result = playRound("rock", getComputerChoice());
console.log(result);
});

const scissors = document.querySelector("#scissors").addEventListener("click", function () {
let result = playRound("scissors", getComputerChoice());
console.log(result);
});

const paper = document.querySelector("#paper").addEventListener("click", function () {
let result = playRound("paper", getComputerChoice());
console.log(result);
});



function getComputerChoice(){
  const choices = ["rock", "paper", "scissors"];
  let computerChoice = choices[Math.floor(Math.random() * 3)];
  return computerChoice;
}

const rounds = 5;
let playerScore = 0;
let computerScore = 0;

function playRound(playerSelection, computerSelection) {


  if(playerSelection === computerSelection) {
    return "It's a tie";
  } else if (
    (playerSelection === "rock" && computerSelection === "scissors") ||
    (playerSelection === "paper" && computerSelection === "rock") ||
    (playerSelection === "scissors" && computerSelection === "paper")
  )  {
    playerScore++;
    return `Player wins! ${playerSelection} beats ${computerSelection}`;
  } else {
    computerScore++;
    return `Computer wins! ${computerSelection} beats ${playerSelection}`;
  }
}


function playGame(){
  for(let i = 0; i < rounds; i++){
    if (playerScore > computerScore) {
    return "Player wins the game";
  } else if (computerScore > playerScore) {
     return "Computer wins the game"
    } else {
      return "Game ends in a tie"
    }
  }
}

Looking for guidance.

Receiving map is not a function for a json list that I pull down in React [duplicate]

Right now, I am trying to create a react JS page that pulls down a JSON from a FAST API endpoint and displays the result in the table. Here is the code I have currently:

import {useState, useEffect } from "react";

const URL = 'http://3.141.192.107/get-pga-best-odds'

function playerOddsTable(data) {
  return (
      <div>
          <TableContainer>
              <Table>
                  <TableHead>
                      <TableRow>
                          <TableCell>Golfer</TableCell>
                          <TableCell>Odds</TableCell>
                          <TableCell>Sportsbook</TableCell>
                      </TableRow>
                  </TableHead>
                  <TableBody>
                    {data.map((list, index) => (
                      <TableRow key={index}>
                          <TableCell>{list.Name}</TableCell>
                          <TableCell>{list.Odds}</TableCell>
                          <TableCell>{list.Book}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
              </Table>
          </TableContainer>
      </div>
  )
}



const App = () =>  {
  const [users, setUsers] = useState([]);

  const fetchUsers = async (url) => {
      try {
          const res = await fetch(url);
          const data = await res.json();
          if (data.length > 0) {
              setUsers(data);
          }
          console.log(data);
      } catch (e) {
          console.error(e)
      }
    }


    useEffect(() => {
        fetchUsers(URL);
    }, [])
  


  return (
    <>
    <StyledPaper>
      <h1> Sharp Golf </h1>
    </StyledPaper>
    <Paper>
      {playerOddsTable(users)}
    </Paper>
    </>
  );

}

export default App;

I am currently receiving this error:

data.map is not a function
TypeError: data.map is not a function
    at playerOddsTable (http://localhost:3000/main.c8364f10585f74f71bb8.hot-

It comes from the fact that I try to use map on the data I receive from the URL.

I have manually put a JSON from this website in and been able to properly run my code on it. I have also tried looking at the logs and it appears that the data is able to be fetched. I’m not familiar with javascript at all, this is one of my first projects learning it. I wonder if there is some race condition where it tries to map the data before accessing the API. Any help would be much appreciated.

  • I recently tried setting the default state to an array with a blank object and the error still occurs. Is the data I’m pulling down in the wrong format?

redirect with js to another page, the same way like html attribute

I have created an app with Dynamics 365, and I navigate from one page to another page

with the built in grids etc..

now I need to make a custom button to navigate to a page, so I try to use document.location.href = 'url', but this make a whole other loading experience from opening it with the grids(the navbar gets also reloaded, and the record set option disappear)

so I try to use the developer tool to see how Microsoft use to navigate from a grid row, to the form, and I see that there used a <a> html attribute to navigate,

so my question is how can I get the same behavior by using java script to redirect to a page, as pressing on a <a> link, or how can I make a dummy html <a> tag and click it with js?

here is the copied html, used by the grid to navigate


    <div role="presentation" style="max-width: max-content;"><a
            href="full url"
            class="classes" role="link"
            aria-label="text" tabindex="0"
            data-pa-landmark-active-element="true">
            <div class="classes" role="none"><span class="classes" role="presentation">text</span>
            </div>
        </a></div>

any help will be appreciated

I also try to use the other function form document object(replace etc ) but doesn’t get me the same behavior like a <a> attribute, and i also try to use the Xrm.Navigation but nothing archive my needs

AlpineJS hide button if total is less that offset and limit

I am trying to hide a button if my total number is less than limit + offset,

My button

<div @click="loadMore()" x-show="total > (limit + offset)" class="text-center pt-4">
                 <button class="border border-solid border-slate-700 text-slate-100 hover:bg-slate-800 px-4 py-2"> Load More </button>
            </div>

My data in console

action: filterPosts
limit: 6
post_type_js: videos
offset: 0
category: 1094
total: 28

I believe the way i have my button set is if total is more than limit + offset how, else hide. but the button is not showing.

when i inspect my code

<a class="parent post_no active" data-value="28" @click="total += parseInt($el.dataset.value); filterPosts(1094)">option1</a>

How to save current input.value while typing, into a new global variable?

how do i save the input.value while typing into a new variable(currentInput) so that i can use that new variable globally?

HTML code:
    <h1>Check if your text is a Palindrome:</h1>
    <div id="palindrome-checker">
      <p>Enter your text</p>
      <form id="palindrome-form">
        <input type="text" id="text-input" required value="">
        <button type="button" id="check-btn" >Enter</button>
      </form>

Javascript code:     
   const input = document.querySelector("#text-input");
   const button = document.querySelector("#check-btn");
   const output = document.querySelector("#result");
   const form  = document.querySelector("#palindrome-form");
   let currentInput = "";

   
   input.onkeyup = myFunction

  function myFunction(){
  currentInput = document.querySelector("#text-input").value 
  }

Ask how to resolve persistent high memory usage when reading files from ArrayBuffer in web application

You’ve written logic to convert a file to an ArrayBuffer and process it when the user selects it via a file picker. Initially, you tried to do this using the FileReader API, but you ran into an issue where the memory usage kept increasing and didn’t decrease over time. You changed your code to use Blob.prototype.arrayBuffer() as an alternative, but this still didn’t solve the memory usage issue.

I implemented it using the code below.

async function pickAndReadFileAsArrayBuffer() {
  try {
    // openFilePicker를 호출하여 파일 선택기를 엽니다.
    const [fileHandle] = await window.showOpenFilePicker();
 
    // 선택된 파일을 가져옵니다.
    const file = await fileHandle.getFile();
 
    // FileReader를 사용하여 파일을 ArrayBuffer로 읽습니다.
    const reader = new FileReader();
 
    reader.onload = (e) => {
      const arrayBuffer = e.target.result;
      // ArrayBuffer 처리 로직, 예를 들어 콘솔에 출력
      console.log(arrayBuffer);
 
      // 처리가 완료되면, 이벤트 핸들러를 해제하여 FileReader 객체에 대한 참조를 제거합니다.
      reader.onload = null;
      reader.onerror = null;
    };
 
    reader.onerror = (e) => {
      console.error('File reading failed', e);
 
      // 오류가 발생한 경우에도 이벤트 핸들러를 해제합니다.
      reader.onload = null;
      reader.onerror = null;
    };
 
    reader.readAsArrayBuffer(file);
  } catch (err) {
    // 사용자가 파일 선택을 취소하거나 오류가 발생한 경우
    console.error(err.name, err.message);
  }
}
 
// 함수 호출하여 파일 선택과 ArrayBuffer로의 읽기 과정을 실행
pickAndReadFileAsArrayBuffer();

async function pickAndReadFileInChunks() {
  try {
    // 파일 선택기를 엽니다.
    const [fileHandle] = await window.showOpenFilePicker();
    const file = await fileHandle.getFile();

    const chunkSize = 1024 * 1024; // 1MB
    let startPosition = 0;

    while (startPosition < file.size) {
      const endPosition = startPosition + chunkSize;
      const chunk = file.slice(startPosition, endPosition);
      const arrayBuffer = await chunk.arrayBuffer();
      // 여기서 각 chunk의 ArrayBuffer를 처리합니다.
      console.log(arrayBuffer);
    clearInterval(arrayBuffer)

      startPosition += chunkSize;
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

// 함수 호출하여 파일 선택과 분할 읽기 과정을 실행
pickAndReadFileInChunks();