Best way to make borders for a crossword in CSS?

I am trying to create a “crossword” where only two words cross with each other. I would like the squares to be separated between each other by 1px, but a thick, 5 or 10px border around the crossword itself. Here is a quick demonstration of what I would like to do, made with Excel:

enter image description here

For making the grid, I am creating a rectangle of 6×5 blocks, some of them being invisible, and some being visible:

let word_vertical = "GHIEJ";
let junction_vertical = 4;
let word_horizontal = "ABCDEF";
let junction_horizontal = 5;

let number_of_letters_vertical = word_vertical.length;
let number_of_letters_horizontal = word_horizontal.length;
let letter_junction = word_vertical[junction_vertical - 1];

let board = document.getElementById("board");

for (let i = 0; i < number_of_letters_vertical; i++) {
    let row = document.createElement("div");
    row.className = "letter-row";

    for (let j = 0; j < number_of_letters_horizontal; j++) {
        let box = document.createElement("div");
        if (i === junction_vertical - 1 || j === junction_horizontal - 1){
            box.className = "letter-box";
            if (j === junction_horizontal - 1) {
                box.innerText = word_vertical[i];
            } else if (i === junction_vertical - 1){
                box.innerText = word_horizontal[j];
            }
        } else {
            box.className = "empty-box";
        }

        row.appendChild(box)
    }

    board.appendChild(row)
}

And here is the CSS:

.letter-box {
    color: black;
    border: 1px solid black;
    background-color: white;
    font-size: 3.5rem;
    font-weight: 800;
    height: 5rem;
    width: 5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    text-transform: uppercase;
}

.empty-box {
    border: 1px solid transparent;
    height: 5rem;
    width: 5rem;
    display: flex;
    justify-content: center;
    align-items: center;
}

This turns out to look like this:

enter image description here

As you can see, the borders around are very thin (1px) and the borders between two cells are 2px (1px for each cell contributing). I have tried a few things, including applying directional borders to the empty boxes but that gets complex very fast. Any ideas? Thanks 🙂

Azure File Share Access Issue: MissingRequiredHeader Error When Fetching File Properties

I’m trying to access an Azure File Share using the Azure SDK for JavaScript/TypeScript. My goal is to fetch the properties of a specific file. However, I’m encountering a MissingRequiredHeader error when attempting to get the file properties.

const { ShareServiceClient } = require("@azure/storage-file-share");
const { ClientSecretCredential } = require("@azure/identity");

// Azure credentials
const tenantId = "";
const clientId = "";
const clientSecret = "";

// Storage configuration
const storageAccountName = '';
const fileShareName = 'documents';

// File path
const directoryPath = "uploadcontent/xyz/2024/MAR/abc";
const fileName = "abc.pdf";

// Create a ClientSecretCredential
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

// Create ShareServiceClient
const shareServiceClient = new ShareServiceClient(
  `https://${storageAccountName}.file.core.windows.net`,
  credential
);

async function getFileProperties() {
  try {
    const shareClient = shareServiceClient.getShareClient(fileShareName);
    const directoryClient = shareClient.getDirectoryClient(directoryPath);
    const fileClient = directoryClient.getFileClient(fileName);
    const properties = await fileClient.getProperties();
    console.log("File properties:", properties);
  } catch (error) {
    console.error("An error occurred:", error.message);
    if (error.details) {
      console.error("Error details:", error.details);
    }
  }
}

getFileProperties().catch(console.error);

Error Message
When running this code, I get the following error:

An error occurred:
Error details: {
  errorCode: 'MissingRequiredHeader',
  'transfer-encoding': 'chunked',
  server: 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': '730b5b9b-901a-0046-7257-1ac07c000000',
  'x-ms-client-request-id': '2b148100-1625-45e3-8215-a8a3edc25e99',
  'x-ms-version': '2024-11-04',
  date: 'Wed, 09 Oct 2024 14:28:06 GMT',
  body: undefined
}

What I’ve Tried

I’ve verified that the service principal (clientId) has the necessary permissions to access the file share.
I’ve double-checked that the file path and share name are correct.
I’ve tried adding custom headers to the request, including ‘x-ms-version’ and ‘x-ms-date’, but the issue persists.

Question

What could be causing this MissingRequiredHeader error?
Are there any specific headers or configurations I need to include when using ClientSecretCredential with Azure File Share?
Is there a better way to authenticate and access Azure File Share using the JavaScript/TypeScript SDK?

Any help or guidance would be greatly appreciated. Thank you!

Possible to use Singleton for logger when we expect it to contain request context?

I have an Express API that uses Pino logger that currently uses a request handler to assign a Pino logger to the request itself (within a context) that uses a generated request ID as its child.

routes

const router = express.Router();
const controller = new Controller();

router.get('/', requestHandler(controller.doStuff));
router.get('/path', requestHandler(controller.doOtherStuff));

logger

export default pino({});

requestHandler

const requestHandler = (fn) => async (req, res, next) => {
  const reqId = // some random UUID;
  const ctx = { logger: logger.child(reqId), reqId) };

  return res.json({ data: ctx });

The logger is then accessed via the ctx in functions like doStuff and doOtherStuff

const doStuff = (req, ctx) => {
  ctx.logger.info('doing stuff now');
  ...
}

My issue/worry is that when I want to perform logging at a deeper, such as utils that are imported from another file, I will have to pass this logger through the chain and that feels a bit messy.

For example:

import {extraStuffUtil} from './utils';

const doStuff = (req, ctx) => {
  ctx.logger.info('doing stuff now');

  extraStuffUtil(ctx.logger, {value: 123});
}

// utils.js
const extraStuffUtil = (logger, val) => {
  logger.info(`doing extra stuff with value {val}`);
  ...
}

Ideally, I would like the logger to be a Singleton so I can “instantiate” it from any file and have the same “context”… Would it be possible here?

Stripe Integration – Elements cannot be mounted in a ShadowRoot. Please mount in the Light DOM

I am trying to use Stripe Elements in a react application created with vite. Here is my current code.

 import { CardCvcElement, CardExpiryElement, CardNumberElement, useElements, useStripe } from "@stripe/react-stripe-js";
import { StripeCardNumberElement } from "@stripe/stripe-js";
import { useState } from "react";
import { Button, Input, Modal, notify } from "../../shared";
import { PaymentMethodModalProps } from "../../types/paymentMethod.types";
import { transformError } from "../../utils/errors";
const stripeKey = import.meta.env.VITE_APP_STRIPE_KEY;
const PaymentMethodModal = ({
  paymentMethodModal,
  setPaymentMethodModal,
  onPaymentMethod,
  type,
}: PaymentMethodModalProps) => {
  const stripe = useStripe();
  const elements = useElements();
  const [cardHolderName, setCardHolderName] = useState("");
  const handleUpdatePaymentMethod = async (event: any) => {
    event.preventDefault();
    try {
      if (!stripe || !elements) {
        return;
      }
      console.log("cardElement", elements.getElement(CardNumberElement));
      const cardNumberElement: StripeCardNumberElement | null = elements.getElement(CardNumberElement);

      if (cardNumberElement === null) return;

      const { token } = await stripe.createToken(cardNumberElement);
      onPaymentMethod(token?.id || "", cardHolderName);
      setPaymentMethodModal && setPaymentMethodModal(false);
    } catch (error) {
      notify(transformError(error), "error");
    }
  };

  return (
    <Modal
      heading={`${type === "add" ? "Add" : "Update"} payment method`}
      open={paymentMethodModal || false}
      setOpen={setPaymentMethodModal || (() => {})}
      okText={`${type === "add" ? "Add" : "Update"}`}
      onOk={(e) => handleUpdatePaymentMethod(e)}
    >
      <>
        <div className="flex justify-between items-center space-x-3">
          <Input
            onChange={(e) => {
              setCardHolderName(e.target.value);
            }}
            className="mt-3 w-full"
            id="name"
            required={true}
            label="Card holder name"
          />
        </div>
        <div className="mt-3 pr-6 max-w-full">
          <p className="py-1">Card number</p>
          <CardNumberElement className="border-white-400 px-3 py-3 border border-solid rounded-lg w-full" />
        </div>
        <div className="flex space-x-3 mt-3 w-full">
          <div className="w-1/2">
            <p className="py-1">Exp. Date</p>
            <CardExpiryElement className="border-white-400 px-3 py-3 border border-solid rounded-lg" />
          </div>
          <div className="w-1/2">
            <p className="py-1">CVV/CVS</p>
            <CardCvcElement className="border-white-400 px-3 py-3 border border-solid rounded-lg" />
          </div>
        </div>
        <Button onClick={(e) => handleUpdatePaymentMethod(e)}>Whatever</Button>
      </>
    </Modal>
  );
};

export default PaymentMethodModal;

I have wrapped this component inside Elements

import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";

 <Elements stripe={loadStripe(stripeKey)}>
{component wrapped here}
</Elements>

For some reason, I face this error and the application crashed.

IntegrationError: Elements cannot be mounted in a ShadowRoot. Please mount in the Light DOM.

What I have tried.
As I am using the modal, I tried to use this component outside modal. The error still shows up but the form is rendered correctly and card was working fine.

Gap under product template only [closed]

I’m unable to find the source of this giant white gap underneath this website.

Site link here

I have used layers in inspect element, looked for fixed and visibility hidden or opacity 0 items, disabled margins and padding using * {} for all elements, disabled javascript on render, disabled apps and plugins, nothing conventional has worked. I’m starting to wonder if it is tied to Shopify’s web-pixels-manager security? If someone more knowledgable is able to find the source of the issue I would be very grateful for the assistance.

Wget websites, but click ‘index.html’ shows nothing but pictures

How can I download a website to local system, which may use javascript to show the entire content?

The local txt file should be used to extract data. I get the entire file, but why I cannot see the page offline? Can this problem be solved using wget or some other Python libs?

wget --mirror --convert-links --adjust-extension --page-requisites --span-hosts -nd -k -P./LOCAL --default-page=test.html 'url' 

I use this code to download a websites to local system, but when I open the ‘index.html’ I can not see any texts or buttons. I CTRL+S the websites and see something in file management’s preview, but I open the ‘index.html’, and get the same page as the last method.
I am sure that my Chrome does not forbid javascript

I want to use the local website to extract data and save it to csv, the first step is downloading it .

onSubmit fires event only when losing focus

I know there is a lot of questions regarding this topic, but I have a specific question regarding javascript events.

I work on a html code, which has an input tag where the customer should enter an amount.

<input name="amount"
value="#{givenValue}"
converter="#{decimalConverter}"
styleClassInput="js-3-step-calc-amount-field"
onchange="rmc_doValueChange()"
required="true" />

The amount should always be rounded up to the next hundreds, e.g, customer enters 588,98, then it should send in the request 600.

Now it is with the onchange event, which of course does not work when an Enter is hit or the next button is pressed without losing focus on the input.

I have read that onkeyup is an option, but then it will update in every digit, which is not optimal.

Is there a way to call a certain method even when the focus is not lost on the input element and at the same time to not update by every digit or button press, because then when a user gives 876,99, it should round up after 8, 87, 876 and 876,9 too.

Any ideas?
Thank you a lot!

Is there a function on a ERC721 Smart Contract that I can fix this issue with?

I have been having an issue for a month with my smart contract. It isn’t allowing any of my community members to list or sweep any NFTs from this collection on any marketplaces at all.

It takes their gas money and will not list, and for sweeping it takes their gas money, returns their funds and doesn’t give them the NFTs they are trying to buy. Does this have anything to do with the function SetApprovalForAll?

When I dug deeper into their transactions I saw that the tx said “one or two errors occurred. Execution reverted”

https://etherscan.io/address/0xb56011fbfdafe460b905a40a4845a49c94712272#events

Has anyone ever heard of this happening before?

I tried it for myself also just to see if this would happen and in fact this is what happened This was on Blur marketplace i tried buying 4 NFTs from my collection that were listed on the secondary market and the same thing happened. Execution reverted

Re-position dropdown elements so that they’re under a dropdown control

I inherited this application and I’m just a beginner when it comes to C# and Bootstrap, so please explain it like I’m an idiot, because I am. 🙂

I’ve got a dropdown control that reads its elements from a table. The code for such is this:

<tr>
    <td>
        <asp:Label ID="Label23" runat="server" Text="Escalation Reason"></asp:Label>
    </td>
    <td>
        <asp:DropDownList ID="DropDownList_Escalation_Reason" runat="server" CssClass="form-control input-sm" Width="250px">
        </asp:DropDownList>
    </td>
</tr>

When I click on the dropdown, the options pop up above and to the left of the box. I want them to be directly below the dropdown box, so it looks more like your standard out-of-the-box dropdown.

I took a look at this page, but it only seems to deal with buttons that act as dropdowns, and they all had static list items. I’m reading mine from a table into a dropdown control, so it’s not what I need to do.

https://getbootstrap.com/docs/4.0/components/dropdowns/

Can anyone tell me how to get a Bootstrap dropdown to position the selectable list directly below the dropdown control?

EDIT: The above code produces the following HTML when run:

<tr>
    <td>
        <span id="Label23">Escalation Reason</span>
    </td>
    <td>
        <select name="DropDownList_Escalation_Reason" id="DropDownList_Escalation_Reason" class="form-control input-sm" style="width:250px;">
            <option value="0">-----</option>
            <option value="3">Billing needs update to complete client bill</option>
            <option value="9">Client Escalated Request</option>
            <option value="2">Client Facing</option>
            <option value="8">Impact to Client</option>
        </select>
    </td>
</tr>

Set().union() fails with .size property is NaN

I’m creating a set from two arrays, and I’m encountering a confusing TypeError:

const a_list = [1, 2, 3];
const b_list = [3, 4, 5];
const combined = new Set()
    .union(a_list)  // <<<< Error is thrown here.
    .union(b_list);

This fails with the error:

Uncaught TypeError: The .size property is NaN
    at Set.union (<anonymous>)
    at <anonymous>:2:6

How can the set’s .size property be NaN? When I test it in the console, the default size is 0:

> new Set().size
< 0

404 not found error while trying to get recruiter profile

  1. I have a function that is suppose to get recruiter profile by Id but each time I try to run the code I kept having 404 error even after when the recruiter is registered and is also in the database and logged in .
  2. still in the same recruiterController I also have function that updates the recruiter profile which includes picture but each time i try testing the function it only updates the picture and leave other information untouched.

Here is the code in the recruiterController

const Recruiter = require('../../models/userModel').Recruiter 
const Company = require('../../models/companyModel')  // Add company model
const { validationResult } = require('express-validator') 
const cloudinary = require('../../helpers/cloudinary') 

// Create Recruiter Profile
const createRecruiterProfile = async (req, res) => {
  try {
    const errors = validationResult(req) 
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, errors: errors.array() }) 
    }

    const { position, companyName } = req.body 

    // Check if company already exists
    let company = await Company.findOne({ name: companyName }) 
    if (!company) {
      company = new Company({
        name: companyName,
        recruiters: [{
          recruiterId: req.user.id, // Link recruiter to company
          position
        }]
      }) 
      await company.save() 
    } else {
      company.recruiters.push({ recruiterId: req.user.id, position }) 
      await company.save() 
    }

    // Retrieve recruiter by ID first to ensure it exists
    let recruiter = await Recruiter.findById(req.user.id) 
    if (!recruiter) {
      return res.status(404).json({ success: false, msg: "Recruiter not found" }) 
    }

    // Update recruiter profile with company info
    recruiter.company = {
      companyId: company._id,
      position
    } 

    // If media is uploaded
    if (req.files && req.files.media) {
      const uploadResult = await cloudinary.uploader.upload(req.files.media.path) 
      recruiter.media = uploadResult.secure_url 
    }

    // Save updated recruiter profile
    await recruiter.save() 

    res.status(201).json({ success: true, data: recruiter }) 
  } catch (error) {
    res.status(500).json({ success: false, msg: error.message }) 
  }
} 

// Get Recruiter Profile by ID
const getRecruiterProfileById = async (req, res) => {
  try {
    // Extract recruiter ID from route parameters
    const recruiterId = req.params.id 
    

    // Find the recruiter by ID and populate the company details
    const recruiter = await Recruiter.findById(recruiterId) 
    
    if (!recruiter) {
      return res.status(404).json({ success: false, msg: 'Recruiter profile not found' }) 
    }

    // Return the recruiter profile data
    res.status(200).json({ success: true, data: recruiter }) 
  } catch (error) {
    res.status(500).json({ success: false, msg: error.message }) 
  }
} 

// Update Recruiter Profile Function
const updateRecruiterProfile = async (req, res) => {
  try {
    const errors = validationResult(req) 
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, errors: errors.array() }) 
    }

    let updateData = {} 

    // If position is being updated, explicitly update the nested company.position field
    if (req.body.position) {
      updateData['company.position'] = req.body.position 
    }

    // If companyName is being updated, check for the company and update companyId
    if (req.body.companyName) {
      let company = await Company.findOne({ name: req.body.companyName }) 
      if (!company) {
        company = new Company({ name: req.body.companyName }) 
        await company.save() 
      }
      updateData['company.companyId'] = company._id 
    }

    // Check if media is being updated
    if (req.files && req.files.media) {
      const uploadResult = await cloudinary.uploader.upload(req.files.media.path) 
      updateData.media = uploadResult.secure_url 
    }

    // Update the recruiter with the specified fields
    const recruiter = await Recruiter.findByIdAndUpdate(req.user.id, { $set: updateData }, { new: true }) 

    if (!recruiter) {
      return res.status(404).json({ success: false, msg: 'Recruiter not found' }) 
    }

    res.status(200).json({ success: true, data: recruiter }) 
  } catch (error) {
    res.status(500).json({ success: false, msg: error.message }) 
  }
} 



module.exports = {
  getRecruiterProfileById,
  createRecruiterProfile,
  updateRecruiterProfile
} 

the above is the code i tried

what i was expecting is for the code to printout the recruiter profile requested and not printout a 404 error even after when that particular recruiter is in the database and i also expect that when updated it should not only update the picture but also update all other field that needs to be updated.

here is the recruiterModel

const mongoose = require('mongoose')
const Project = require('./projectModel')
const Company = require('./companyModel')

const userSchema = new mongoose.Schema({

  name:{
    type: String,
    required: true
  },

  email:{
    type: String,
    required: true
  },

  password:{
    type: String,
    required: true
  },

  role:{
    // type: Number,
    // default: 0 //0 -> Recruiter, 1 -> Admin, 2 -> Student
      type: String,
      enum: ['admin', 'student', 'recruiter'],
      default: 'recruiter',
  }

}, { discriminatorKey: 'role' })

const adminSchema = new mongoose.Schema({
  managedStudents: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student'
  }],
  managedRecruiters:[{
    type:mongoose.Schema.Types.ObjectId, 
    ref: 'Recruiter'
  }]
})

const studentSchema = new mongoose.Schema({
  profile:{
    bio: String,
    skills:[String],
    projects:[{
      type:mongoose.Schema.Types.ObjectId,
      ref: 'Project'
    }]
  }
})

const recruiterSchema = new mongoose.Schema({
  approved: {
    type: Boolean,
    default: false
  },
  requests: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student'
  }],
  company: {
    companyId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Company'
    },
    position: {
      type: String,
      required: true
    }
  }
})


const User = mongoose.model('User', userSchema)
const Admin = User.discriminator('Admin', adminSchema)
const Student = User.discriminator('Student', studentSchema)
const Recruiter = User.discriminator('Recruiter', recruiterSchema)

module.exports = {
  User,
  Admin,
  Student,
  Recruiter
}

and this the companyModel

const mongoose = require('mongoose')
const companySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  recruiters: [{
    recruiterId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Recruiter'
    },
    position: {
      type: String,
      required: true
    }
  }]
})

module.exports = mongoose.model('Company', companySchema)

Multiple Data Fetching with useSWR in React Hook Leading to Undefined Data

I’m developing a React component ClinicalViewsSummary that retrieves patient encounter data using the useSWR hook. The child component EncounterValuesTile fetches data with various params it has but sometimes receives undefined values, even when the params have not changed, and the data exists. Based on research, hooks should not do data fetching on the bottom level, but i cant avoid it in this case. As a result of looping, the hook is called multiple times before previous requests are resolved and some data is undefined

My main component looks like this :

const ClinicalViewsSummary: React.FC<OverviewListProps> = ({ patientUuid }) => {
  const config = useConfig();
  const { t } = useTranslation();
  const tilesDefinitions1 = config.tilesDefinitions;
  const tilesDefinitions = useMemo(
    () => [
      {
        tileHeader: 'characteristicsTitle',
        columns: [
          {
            id: 'currentRegimen',
            hasSummary: true,
            title: 'currentRegimenTitle',
            encounterType: 'e22e39fd-7db2-45e7-80f1-60fa0d5a4378',
            concept: '164515AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            summaryConcept: {
              primaryConcept: '164515AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            },
          },
          {
            id: 'artCohort',
            title: 'ArtCohortTitle',
            encounterType: 'e22e39fd-7db2-45e7-80f1-60fa0d5a4378',
            concept: '159599AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            isDate: true,
            conceptMappings: [
              '159599AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              '162572AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              '164516AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              '164431AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              '160738AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            ],
          },
          {
            id: 'dsdModel',
            title: 'dSDModelTitle',
            hasSummary: true,
            encounterType: 'e22e39fd-7db2-45e7-80f1-60fa0d5a4378',
            concept: 'dfbe256e-30ba-4033-837a-2e8477f2e7cd',
            summaryConcept: {
              primaryConcept: '166448AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            },
          },
          {
            id: 'populationType',
            title: 'populationTypeTitle',
            encounterType: 'e22e39fd-7db2-45e7-80f1-60fa0d5a4378',
            concept: '164431AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            hasSummary: true,
            summaryConcept: {
              primaryConcept: '166433AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              secondaryConcept: '2bf14240-b2b2-42b2-8cf3-b5f8a0cb7764',
            },
          },
        ],
      },
      {
        tileHeader: 'hivMonitoring',
        columns: [
          {
            id: 'viralLoad',
            title: 'currentViralLoad',
            encounterType: '3596fafb-6f6f-4396-8c87-6e63a0f1bd71',
            concept: '1305AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            hasSummary: true,
            summaryConcept: {
              primaryConcept: '163724AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              isDate: true,
            },
          },
          {
            id: 'lastCD4Count',
            title: 'lastCD4CountTitle',
            hasSummary: true,
            encounterType: '3596fafb-6f6f-4396-8c87-6e63a0f1bd71',
            concept: '5497AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            summaryConcept: {
              primaryConcept: '163724AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              isDate: true,
            },
          },
        ],
      },
      {
        tileHeader: 'lastVisitDetails',
        columns: [
          {
            id: 'nextAppointmentDate',
            title: 'nextAppointmentDateTitle',
            hasSummary: true,
            encounterType: 'cb0a65a7-0587-477e-89b9-cf2fd144f1d4',
            concept: '5096AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
            summaryConcept: {
              primaryConcept: '5096AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
              isDate: true,
              hasCalculatedDate: true,
            },
          },
          {
            id: 'programStatus',
            title: 'programStatusTitle',
            encounterType: 'a221448d-512b-4750-84bf-d29be9f802b3',
            concept: '163105AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
          },
        ],
      },
    ],
    [],
  );

  const tilesData = useMemo(
    () =>
      tilesDefinitions?.map((tile: any) => ({
        title: tile.tileHeader,
        columns: getEncounterTileColumns(tile, t),
      })),
    [],
  );

  return (
    <>
      {tilesData?.length > 0 &&
        tilesData?.map((tile, index) => (
          <MemoizedEncounterTile
            key={index}
            patientUuid={patientUuid}
            columns={tile.columns}
            headerTitle={tile.title}
          />
        ))}
    </>
  );
};

My child components that display columns in different tiles look like this :

const EncounterTile: React.FC<EncounterTileProps> = ({ patientUuid, columns, headerTitle }) => {
  return (
    <div className={styles.tileContainer}>
      <Tile className={styles.tile}>
        <div className={styles.cardTitle}>
          <h4 className={styles.title}> {headerTitle} </h4>
        </div>
        <Column className={styles.columnContainer}>
          {columns.map((column, ind) => (
            <EncounterValuesTile key={ind} patientUuid={patientUuid} column={column} />
          ))}
        </Column>
      </Tile>
    </div>
  );
};

export const MemoizedEncounterTile = React.memo(EncounterTile);

export const EncounterValuesTile: React.FC<EncounterValuesTileProps> = ({ patientUuid, column }) => {
  const { lastEncounter, isLoading, error, isValidating } = useLastEncounter(patientUuid, column.encounterUuid);

  if (isLoading || isValidating) {
    return <CodeSnippetSkeleton type="multi" data-testid="skeleton-text" />;
  }

  if (error || lastEncounter === undefined) {
    return (
      <div className={styles.tileBox}>
        <div className={styles.tileBoxColumn}>
          <span className={styles.tileTitle}> {column.header} </span>
          <span className={styles.tileValue}>--</span>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.tileBox}>
      <div className={styles.tileBoxColumn}>
        <span className={styles.tileTitle}> {column.header} </span>
        <span className={styles.tileValue}>
          <LazyCell lazyValue={column.getObsValue(lastEncounter)} />
        </span>
        {column.hasSummary && (
          <span className={styles.tileTitle}>
            <LazyCell lazyValue={column.getSummaryObsValue(lastEncounter)} />
          </span>
        )}
      </div>
    </div>
  );
};

How can I ensure that these requests are made sequentially, so that I only fetch data when the previous fetch has completed?
Is there a way to optimize my hooks to prevent multiple requests for the same encounter type?
Are there best practices to handle this kind of situation in React when using hooks like useSWR?
Any advice or solutions would be greatly appreciated!

Attaching click event handlers in Astro pages

In the component template section of an Astro page, I am adding the following script:

// src/pages/foo.astro
<script>
document.addEventListener('DOMContentLoaded', function() {
    const myElement = document.getElementById('myId');
    
    if (myElement) {
        myElement.addEventListener('click', function() {
            console.log('Clicked on element with ID "myId"');
            // Add your desired functionality here
        });
    } else {
        console.warn('Element with ID "myId" not found');
    }
});
</script>

It’s a generic script attaching a click event handler to myId element if found.
Note that the event is attached when the DOM content is loaded, via the DOMContentLoaded listener, to be sure that myId is created when due.

If I navigate directly to the page, I can read the messages sent by console.log(), depending on the presence of myId.
However, linking to foo.astro from another page:

// src/pages/bar.astro
...
<a href="/foo.astro">Go to foo</a>

then, when I click on the link to foo, the DOMContentLoaded event is not fired and I see no console messages.

This happens also when I look for elements with different functions, such asdocument.querySelectorAll().

So, what is the correct way to add event handlers in Astro?
Should I avoid waiting for DOM loading and expect that Astro will inject my page scripts when it’s the right time? And how is this decided by Astro?

what is the best approach to obtain all zip codes within a specified latitude, longitude, and radius? [closed]

I am looking for a solution to find nearby zip codes within a specified radius based on my current location. I have tried using the Places API, but the results are limited. I’m attaching my code below for reference.
I am currently using the Google Places API to search for places within a given radius based on latitude and longitude.
For each place returned by the Places API, I then use the Google Geocoding API to retrieve its postal code.
I handle pagination using the next_page_token to ensure that I fetch all results within the specified radius.
All I want is to search for nearby zip codes based on a radius. Can you suggest if Google Maps API can be used for this, or if there are any other reliable sources available for the US only?
enter image description here