Next 15 + TS project update returning undefineds

I’m trying to update a next 13 pages router project to next 15 + typescript just for training purposes, but I’m getting a lot of undefineds.

This project is somewhat famous from an Udemy Course. I’m getting the posts prop as undefined when trying to use fs, path and gray matter to get metadata and text from an markdown file inside root/postsDB.

This is the util file with the functions that fetch the md files:

posts-util.ts

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

const postsDirectory = path.join(process.cwd(), 'postsDB');
console.log("Posts directory path:", postsDirectory); 

if (!fs.existsSync(postsDirectory)) {
    console.error("Posts directory does not exist:", postsDirectory); 
  }

function getPostData(fileName: string) {
  const filePath = path.join(postsDirectory, fileName);
  const fileContent = fs.readFileSync(filePath, 'utf-8');
  const { data, content } = matter(fileContent);

  const postSlug = fileName.replace(/.md$/, '');

  const postData = {
    slug: postSlug,
    date: data.date,
    isFeatured: data.isFeatured || false,
    ...data,
    content,
  };

  return postData;
}

export function getAllPosts() {
  const postFiles = fs.readdirSync(postsDirectory);
  console.log("Post files:", postFiles);

  const allPosts = postFiles.map(postFile => {
    return getPostData(postFile);
  });

  console.log("All posts:", allPosts); 

  const sortedPosts = allPosts.sort((postA, postB) => (postA.date > postB.date ? -1 : 1));

  return sortedPosts;
}

export function getFeaturedPosts() {
  const allPosts = getAllPosts();
  console.log("All posts in getFeaturedPosts:", allPosts); 

  const featuredPosts = allPosts.filter(post => post.isFeatured);
  console.log("Featured posts:", featuredPosts); 

  return featuredPosts;
}

This is the index.tsx (HomePage) file

import FeaturedPosts from "@/components/home-page/featured-posts";
import Hero from "@/components/home-page/hero";
import { Post } from "@/interfaces/Post";
import { getFeaturedPosts } from "@/lib/posts-util";

interface HomePageProps {
  posts: Post[];
}

export default function HomePage({ posts }: HomePageProps) {
  console.log("HomePage posts:", posts); 

  return (
    <>
      <Hero />
      <FeaturedPosts posts={posts} />
    </>
  );
}

export async function getStaticProps() {
  console.log("getStaticProps called"); 
  const featuredPosts = getFeaturedPosts();
  console.log("Featured posts in getStaticProps:", featuredPosts); // Debugging line

  return {
    props: {
      posts: featuredPosts,
    },
    revalidate: 1800,
  };
}

And these are components that render the posts.

posts-grid.tsx

import PostItem from "./post-item";

import { Post } from "@/interfaces/Post";

import styles from "@/styles/posts-grid.module.css";


interface PostsGridProps {
  posts: Post[];
}

export default function PostsGrid({ posts = [] }: PostsGridProps) {
  return (
    <ul className={styles.grid}>
      {posts.map(post => (
        <PostItem key={post.slug} post={post} />
      ))}
    </ul>
  );
}

featured-posts.tsx

import PostsGrid from "../posts/posts-grid";
import { Post } from "@/interfaces/Post";
import styles from "@/styles/featured-posts.module.css";

interface FeaturedPostsProps {
  posts: Post[];
}

export default function FeaturedPosts({ posts }: FeaturedPostsProps) {
  console.log("FeaturedPosts posts:", posts);

  return (
    <section className={styles.latest}>
      <h2>Featured Posts</h2>
      <PostsGrid posts={posts} />
    </section>
  );
}

The full project can be found here:

https://github.com/rodhis/next-blog

I think it’s important to say that no console.log and console.error from posts-util.ts are appearing on the console!

Can anyone say what’s wrong?

Have multiple elements with different parents have same width as widest

Note that for items in a list or with otherwise the same parent there are existing questions such as this one – However they don’t cover what I’m asking as they all cover items in a table or otherwise sharing a parent.

I have multiple buttons on my page and due to some frankly boneheaded design decisions made 20 years ago they’re all in different containers that I can’t touch.

Example:

<button class="myButton">really long text means really wide button</button>
<!-- elsewhere, under a different parent -->
<button class="myButton">small button</button>
<!-- even further away parented to yet another element -->
<button class="myButton">kinda medium text</button>

How can I, in either CSS or plain JavaScript, make all of the buttons the width of the widest one? The number of buttons varies but is thankfully determined before the page is rendered, and the text is known ahead of time (e.g. the widest button will always say “really long text means really wide button”) so it doesn’t need to account for dynamic changes and could even be some hardcoded hacky method (although accounting for dynamic changes would be more useful for future readers).

How to determine the best Plotly chart type programmatically based on dataset characteristics?

import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
import { UtilsService } from '../services/utils.service';
import Plotly from 'plotly.js-dist-min';

@Directive({
  selector: '[appDynamicPlotly]'
})
export class DynamicPlotlyDirective implements OnInit {  
  @Input() public data: any;
  @Input() public group: string = 'Month';
  protected plot: any;
  private currentType: string = 'bar'; // Default plot type
  private currentMode: string = ''; // Default plot type

  constructor(private elementRef: ElementRef, private utilsService: UtilsService, private renderer: Renderer2) {}

  ngOnInit() {
    this.plot = this.elementRef.nativeElement;
    this.renderPlot();
  }

  private renderPlot() {
    const trace: any = this.getTrace();

    const layout: Partial<Plotly.Layout> = this.getLayout();

    const config: Partial<Plotly.Config> = {
      responsive: true,
      displayModeBar: false,
      displaylogo: false
    };

    Plotly.react(this.plot, trace, layout, config);
  }

  private getTrace() {
    switch (this.currentType) {
      case 'pie':
        return [
          {
            labels: this.data[this.group], // Grouped data as labels
            values: this.data.storage_state_kg, // Corresponding values
            type: 'pie',
            // textinfo: 'label+percent',
            textposition: 'outside',
            automargin: true,
            marker: { colors: ['#046CC4', '#F066AC', '#3C8454', '#64323A', '#182D44'] },
            hovertemplate: '%{label}<br>H₂ Production: %{value}<extra></extra>'
          }
        ];
      case 'line':
        return [
          {
            x: this.data[this.group],
            y: this.data.storage_state_kg,
            type: 'scatter',
            mode: 'lines',
            name: 'H₂',
            line: { color: '#046CC4', width: 2 },
            hovertemplate: '%{x}<br>H₂ Production: %{y}<extra></extra>'
          }
        ];
      case 'scatter':
        return [
          {
            x: this.data[this.group],
            y: this.data.storage_state_kg,
            type: 'scatter',
            mode: 'markers',
            name: 'H₂',
            marker: { color: '#046CC4', size: 8 },
            hovertemplate: '%{x}<br>H₂ Production: %{y}<extra></extra>'
          }
        ];
      case 'waterfall':
        return [
          {
            x: this.data[this.group],
            y: this.data.storage_state_kg,
            type: 'waterfall',
            name: 'H₂',
            measure: Array(this.data.storage_state_kg.length).fill('relative'),
            connector: { line: { color: '#7F7F7F' } },
            hovertemplate: '%{x}<br>H₂ Production: %{y}<extra></extra>',
            increasing: { marker: { color: '#046CC4' } },
            decreasing: { marker: { color: '#E74C3C' } },
            totals: { marker: { color: '#2ECC71' } }
          }
        ];
      case 'bar':
      default:
        return [
          {
            x: this.data[this.group],
            y: this.data.storage_state_kg,
            type: 'bar',
            name: 'H₂',
            marker: { color: '#046CC4' },
            hovertemplate: '%{x}<br>H₂ Production: %{customdata}<extra></extra>',
            customdata: this.data.storage_state_kg.map((val: number) =>
              Number.isInteger(val) ? val.toFixed(0) : val.toFixed(3)
            )
          }
        ];
    }
  }

  private getLayout(): Partial<Plotly.Layout> {
    if (this.currentType === 'pie') {
      return {
        title: {
          text: 'Dynamic Plot',
          font: { size: 14 },
          x: 0.5,
          xanchor: 'center'
        },
        showlegend: true,
        margin: { t: 50, b: 50, l: 60, r: 70 },
        plot_bgcolor: '#F8F8F8',
        paper_bgcolor: '#F8F8F8'
      };
    } else {
      return {
        title: {
          text: 'Dynamic Plot',
          font: { size: 14 },
          x: 0.5,
          xanchor: 'center'
        },
        xaxis: {
          tickmode: 'array',
          tickvals: this.data[this.group],
          ticktext: this.data[this.group].map((val: any) =>
            this.utilsService.getDateTextForChart(val, this.group)
          ),
          tickfont: { size: 14, color: '#000000' },
          showgrid: true,
          tickangle: 0
        },
        yaxis: {
          title: {
            text: 'H₂ Storage State (MT H₂)',
            font: { size: 16, color: '#000000' },
            standoff: 30
          },
          tickfont: { size: 14, color: '#000000' },
          showgrid: false,
          rangemode: 'tozero'
        },
        dragmode: undefined,
        barmode: this.currentType === 'bar' ? 'stack' : undefined,
        margin: { t: 50, b: 50, l: 60, r: 70 },
        bargap: 0.7,
        plot_bgcolor: '#F8F8F8',
        paper_bgcolor: '#F8F8F8'
      };
    }
  }

  changePlotType(type: string, mode: string) {
    this.currentType = type; // Update the plot type
    this.currentMode = mode; // Update the plot type
    this.renderPlot(); // Re-render the plot with the new type
  }
}

I’m working on a project using Plotly and Angular, where I need to allow users to switch between different chart types dynamically (e.g., bar, pie, scatter, waterfall, etc.).

Here I’m manually providing a few options that supports array type for x&y. Instead of this, is there any external library, plugin, or built-in feature in Plotly that can suggest appropriate chart types based on the structure or type of the dataset? For example, if the data is categorical vs. numerical, the tool should recommend bar or pie charts.

Facing flickering in virtual scrolling and other issues too, anyone knows?

I’m trying to implement virtual scrolling in a generalized way so that all my pages with table can access it. I know I’m calling the scroll event repeatedly for scrolling even a small pixel which I shouldn’t be and I’m using a map as buffer/cache and my advisor insisted on using a circular double linked list so I have used that just to store and update the rows. The table keeps flickering when I reach the end as it’s trying to fetch more rows I guess which is causing error. :(. someone please help. I’ll share my code with you

implementing virtual scrolling but facing data fetching and scroll height issues

How To Access Item In An Object When Key Is String? [duplicate]

I’m receiving this:

FormData {
  MessagingServiceSid: '12345',
  RetryCount: '0',
  EventType: 'onConversationAdded',
  State: 'active',
  Attributes: '{}',
  DateCreated: '2025-02-04T19:19:12.867Z',
  ChatServiceSid: '12345',
  'MessagingBinding.ProxyAddress': '12345',
  'MessagingBinding.Address': '12345',
  AccountSid: '12345',
  Source: 'SMS',
  ConversationSid: '12345'
}

How do I get the value 12345 out of of ‘MessagingBinding.ProxyAddress’: ‘1235’

Thanks in advance

I’m sure I’ve done this 100 times but for some reason today I just cannot figure it out.

I can get everything else by doing this:

const body = await req.formData()
const EventType = body.EventType

But I cannot figure out how to get they key value when the key is a string like ‘MessagingBinding.ProxyAddress’

React + Axios 429 (Too Many Requests)

I am trying to access the external API “green-api”

This is an API service for WhatsApp. It has an endpoint:
https://1103.api.green-api.com/waInstance1111111/getChatHistory/someInstanceId

When I try to contact via Postman, I get a response and everything works fine, but as soon as I try to do this in the code, I get error 429

const getChatHistory = async () => {
        try {
            return await axios.post(
                `https://1103.api.green-api.com/waInstance1103186061/getChatHistory/f1cc1d63a5d8416e8a70966edc85fa0e71955523321d45c3a2`,
                { chatId: '[email protected]' },
                {
                    withCredentials: false,
                }
            )
        } catch (error: any) {
            console.log(error)
        }
    }

useEffect(() => {
        getChatHistory().then((res) => setMessages(res?.data))
        console.log(messages)
    }, [])

Electron & React Starter Project [closed]

I am starting a project using Electron and React to create a cross platform desktop application. My idea with this app is to connect to a camera, capture images, store the captured images to a specified drive. I have read up a bit on opencv4nodejs and the navigator.mediaDevices.getUserMedia(), not sure what to use. Besides just taking images, i would like to do more in-depth image processing. This application would be used for capturing images of hardcopy documents with the aims to digitize them. So i would like to create a workspace where the documents will be placed and also implement auto-cropping. What do you guys suggest? This would be a bit of a learning opportunity for myself around frontend (javascript) since i am predominantly a backend developer.

Any input would be highly great! 🙂

Can’t use captcha solver api services due to missing the element “data-sitekey”

I’m tryingto to use a captcha solving service but all of them request a code that’s attached to an element called “data-sitekey” that should be in the HTML of a page with recaptcha on it. The problem is that I can’t find data-sitekey for some websites that that require login (such as wsj.com, nytimes.com etc). Is there a way to resolve this issue?

I couldn’t find a way to extract “data-sitekey” for some websites.

best way to loop back to the question in qualtrics

I have a question about Qualtrics looping.

For example, the page can have three questions. The first one is an upload of a file. The second is the text field that allow comments of the file just uploaded. The third question asking whether there is more file to upload. If the answer to the third question is “yes”, then the click of “next page” button will loop back to the same page, with the only minor change of wording in display such as, from the “1st” file to the “2nd” file uploading. If the answer to the third question is “no”, the click of “next page” button will go to next block in the survey.

How do we accomplish this? I think the built-in branch or loop & merge may not work. If we need to use javascript to re-direct the “next page” button, how do we do it?

I looked at the built-in loop & merge in the builder tab and I could not find a way to work-around.

When does firefox (& other browser) fill forms with cached form data?

Problem

I’m making a static webpage that takes some values as inputs & calculates some stuff, and more often than not, I end up reusing the same inputs from one session to the next.

Firefox has been filling my <input>s with the data from the previous session, but I’d like a way to know if Firefox had cached data or not :

  • if there was cached data that is being fed to the form, I want to accept it
  • if there wasn’t, I’d like to trigger a reset to my default form data

What i’ve tried

I’ve tried a very basic use of onload :

<body
        style="[...]"
        onload="init()"
    >

with init being a function that tests if my inputs have a value

function init() {
  if (document.getElementById('myInputA').value &&
      document.getElementById('myInputA').value !== emptyValueA) {
    // use the value that was "stored" for A
  }
  else if (document.getElementById('myInputB').value &&
      document.getElementById('myInputB').value !== emptyValueB) {
    // use the value that was "stored" for B, in a different way
  }
  else {
    // reset inputs to their base value
  }
}

Except this fails miserably, as input() gets triggered at a time when the input elements have their base value (understand their value=... declared in the html element) at that time.

And then later on, I see the oninput method for my inputs get triggered by Firefox inserting the cached values.
Note : Firefox seems to insert those values sequentially, as I can track the oninputs being triggered one by one.

I have not found an event that would happen after that (checked https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState, the “load” event page & related).

Solutions ?

Since Firefox inserting the data into my inputs triggers their oninput methods, I could probably just set the oninput method to a special function for the first time that would be in charge of the initialization, but then I’d still need a way to detect never being triggered, which doesn’t fully solve the problem, unless I use some timeouts & arbitrarily decide a window during which no human would input anything.

I am interested in knowing if other browsers do this kind of thing, how they do it (same page lifecycle ?) & how I could work with this behavior in said other browsers.

How to make script for alternating position articles?

So on my blog page I have alternating articles, but I want the latest post to always be on the left like so:

.rightarticle {
  margin: 10px;
  margin-left: auto;
  width: 400px;
  color: blueviolet;
}

.leftarticle {
  margin: 10px;
  margin-right: auto;
  width: 400px;
  color: blueviolet;
}


article h2 {
  background-color: blueviolet;
  font-size: 20px;
  color: black;
  width: 400px;
}
<article class="leftarticle">
  <h2>lorem ipsum</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris quis diam sit amet neque rhoncus feugiat eget eget libero. Cras bibendum nisl nec erat ultricies vestibulum. Cras pretium volutpat lectus pretium tempus. Suspendisse sit amet sem vehicula, volutpat neque at, consequat turpis. Nulla volutpat orci et dui pharetra, dapibus interdum dolor auctor.</p>
</article>
<article class="rightarticle">
  <h2>lorem ipsum</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris quis diam sit amet neque rhoncus feugiat eget eget libero. Cras bibendum nisl nec erat ultricies vestibulum. Cras pretium volutpat lectus pretium tempus. Suspendisse sit amet sem vehicula, volutpat neque at, consequat turpis. Nulla volutpat orci et dui pharetra, dapibus interdum dolor auctor.</p>
</article>
<article class="leftarticle">
  <h2>lorem ipsum</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris quis diam sit amet neque rhoncus feugiat eget eget libero. Cras bibendum nisl nec erat ultricies vestibulum. Cras pretium volutpat lectus pretium tempus. Suspendisse sit amet sem vehicula, volutpat neque at, consequat turpis. Nulla volutpat orci et dui pharetra, dapibus interdum dolor auctor.</p>
</article>

But I want a script that can do it for me so I don’t have to reassign a class to each article every time I make a new post.

I have very little knowledge of JS and searched google to put things together:

const list = document.getElementById("article").classList;
if ("article" % 2) {
    list.add("rightarticle");
} else {
    list.add("leftarticle");
}

Woocomerce Block Chekout – set customer data by code PHP/Javascript in GUEST MODE

I have this situation: I receive a user from an external portal who arrives on the website with a $_GET parameter containing an encrypted string with various details about the user.

If a “normal user” tries to access the website without this external parameter, they are redirected to an “access denied” page. Otherwise, the information is stored in the session.

Everything works as expected, but now we have a problem.

The user is essentially a guest user in WordPress, but we still have the details provided by the session-stored parameters, including classic data such as name, surname, email, address, and so on.

What I need to do is autocomplete the checkout form using this data.

In a classic WooCommerce checkout, the standard approach would be:

add_filter( 'woocommerce_checkout_fields', 'onboarding_update_fields' );

However, in WooCommerce Block Checkout, this filter is never triggered.

I tried a JavaScript-based approach to fill the input fields once the checkout is loaded, but it seems like the data is “refused”:

const emailBlock = document.querySelector('#contact.wc-block-components-address-form input[type="email"]');

    if (emailBlock) {
        if (!emailBlock.value) {
            emailBlock.value = defaultEmail;
            const changeEvent = new Event('change', { bubbles: true });
            emailBlock.dispatchEvent(changeEvent);

            const inputEvent = new Event('input', { bubbles: true });
            emailBlock.dispatchEvent(inputEvent);

            if (typeof jQuery !== 'undefined') {
                jQuery(emailBlock).trigger('change');
            }
        }
    }

It seems to work because the inputs are filled with values, but visually, the text appears over another one, and if I focus on the email address field, the content disappears. So, this method is not working correctly.

Can anyone suggest the right approach to make this work with WooCommerce Block Checkout? Is there a filter or technique to achieve this?

Deprecation warning from Buffer.from() in NodeJS

I made an Axios call to a url to retrieve data. I get the data back. Then I have this line:

binaryResponse = Buffer.from(response.data);

And when I call the page from the browser, it says Buffer() is deprecated and to use Buffer.from()… which I’m using.

The longer story: Two apps on two different servers. Server 1 calls Server 2 to retrieve and display data. This is necessary due to network and security issues. Being on the local network, I can call either server via the browser. When I call Server 2, my script does what it’s supposed to do and displays the data. When I call Server 1, I SHOULD see that data as well; instead I get that Buffer() error.

The actual error codes are http 500 and subStatus 1013 if that helps. The error text:

(node:28280) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. (Use node --trace-deprecation ... to show where the warning was created) Application has thrown an uncaught exception and is terminated: TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value “undefined” for header “Content-Type” at ServerResponse.setHeader (node:_http_outgoing:702:3) at D:datawebrootMyAppindex.js:34:6 at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

BTW this is all running on Windows using IIS and IISNode.