related products section options hide

Below is the code I need help with. In the list of recommended products, there are some options mistakenly showing up as individual products. I want to hide these options so they do not appear as separate products in the recommended section. For better understanding, here’s a screenshot of the issue: screenshot of issue. Can anyone guide me on how to resolve this problem? Your help would be greatly appreciated.

{%- liquid
  assign products_to_display = recommendations.products_count
  if recommendations.products_count > section.settings.products_to_show
    assign products_to_display = section.settings.products_to_show
  endif

  assign show_desktop_slider = false
  if section.settings.show__slider and products_to_display > section.settings.columns_desktop
    assign show_desktop_slider = true
  endif
-%}

<div class="color-{{ section.settings.color_scheme }} gradient no-js-hidden slider-arrow--{{ section.settings.arrow_position }}">
  <product-recommendations
    data-url="{{ routes.product_recommendations_url }}?section_id={{ section.id }}&product_id={{ product.id }}&limit={{ section.settings.products_to_show }}">
    {% if recommendations.performed and recommendations.products_count > 0 %} 
    <div class="related-products page-width section-{{ section.id }}-padding isolate {% if settings.animations_reveal_on_scroll %} scroll-trigger animate--slide-in{% endif %}">
    {% if recommendations.performed and recommendations.products_count > 0 %}
      <slider-component>
        <div class="{{ section.settings.head_align }} title-wrapper-with-link title-wrapper color-{{ section.settings.heading_color_scheme }} gradient content-container">
          <div class="heading inline-richtext {% if settings.animations_reveal_on_scroll %} scroll-trigger animate--slide-in{% endif %}">
            {%- if section.settings.title != blank -%}
              <h2 class="{{ section.settings.heading_size }}">{{ section.settings.title }}</h2>
            {%- endif -%}
            {%- if section.settings.description -%}
              <div class="{{ section.settings.description_style }} rte">
                  {{ section.settings.description -}}
              </div>
            {%- endif -%}
          </div>
          {%- if section.settings.show__slider and section.settings.arrow_position == 'top' -%}
            <div class="wb_button_combo bcombo_auto">
                <div class="wb_home_sbtn slider-buttons no-js-hidden {% unless show_desktop_slider %} desktop-arrows-hide mobile-arrows-hide {% endunless %}">
                  <button
                  type="button"
                  class="slider-button slider-button--prev button"
                  name="previous"
                  aria-label="{{ 'general.slider.previous_slide' | t }}"
                  id="slider-button--prev-{{ section.id }}"
                  aria-controls="slider-button--prev-{{ section.id }}">
                  <span>{% render 'icon-caret' %}</span>
              </button>
              <button
                  type="button"
                  class="slider-button slider-button--next button"
                  name="next"
                  aria-label="{{ 'general.slider.next_slide' | t }}"
                  id="slider-button--next-{{ section.id }}"
                  aria-controls="slider-button--next-{{ section.id }}">
                  <span>{% render 'icon-caret' %}</span>
              </button>
                </div>
            </div>
          {%- endif -%}
        </div>
        <div class="{% if section.settings.arrow_position == 'inline' %} relative {% endif %}">
        {%- if section.settings.show__slider and section.settings.arrow_position == 'inline' -%}
          <div class="wb_home_sbtn slider-buttons no-js-hidden {% unless show_desktop_slider %} desktop-arrows-hide mobile-arrows-hide {% endunless %}">
            <button
            type="button"
            class="slider-button slider-button--prev button"
            name="previous"
            aria-label="{{ 'general.slider.previous_slide' | t }}"
            id="slider-button--prev-{{ section.id }}"
            aria-controls="slider-button--prev-{{ section.id }}">
            <span>{% render 'icon-caret' %}</span>
            </button>
          </div>
        {%- endif -%}
        <ul id="Slider-{{ section.id }}-{{ block.id }}"
          class="over_scroll {% if section.settings.show__slider %} slider slider--desktop slider--tablet{% endif %} grid product-grid grid--{{ section.settings.columns_desktop }}-col-desktop grid--3-col-tablet grid--{{ section.settings.columns_mobile }}-col-tablet-down"
          >
          {% for recommendation in recommendations.products %}
            <li class="grid__item {% if section.settings.show__slider %} slider__slide{% endif %}" id="Slide-{{ section.id }}-{{ forloop.index }}">
              {% render 'card-product',
                card_product: recommendation,
                card_style: section.settings.card_style,
                media_aspect_ratio: section.settings.image_ratio,
                show_secondary_image: section.settings.show_secondary_image,
                show_vendor: section.settings.show_vendor,
                show_colorswatch: section.settings.show_colorswatch,
                show_rating: section.settings.show_rating,
                show_quick_add: section.settings.enable_quick_add,
                show_variants: section.settings.show_variants,
                picker_type: section.settings.picker_type,
                cardstock_bar: section.settings.cardstock_bar,
                show_count_timer: section.settings.show_count_timer,
                max_stock: section.settings.max_stock,
                limited_stock_cut_off: section.settings.limited_stock_cut_off,
                limited_stock_message: section.settings.limited_stock_message,
                instock_message: section.settings.instock_message,
                continue_selling_message: section.settings.continue_selling_message,
                limited_stock_color: section.settings.limited_stock_color,
                in_stock_color: section.settings.in_stock_color,
                continue_selling_color: section.settings.continue_selling_color,
                quicklook_style: section.settings.quicklook_style,
                color_swatchhover: section.settings.color_swatchhover,
                enable_addtocart: section.settings.enable_addtocart,
                stock_inventory: section.settings.stock_inventory,

                section_id: section.id
              %}
            </li>
          {% endfor %}
        </ul>
        {%- if section.settings.show__slider and section.settings.arrow_position == 'inline' -%}
          <div class="wb_home_sbtn slider-buttons no-js-hidden {% unless show_desktop_slider %} desktop-arrows-hide mobile-arrows-hide {% endunless %}">
          <button
              type="button"
              class="slider-button slider-button--next button"
              name="next"
              aria-label="{{ 'general.slider.next_slide' | t }}"
              id="slider-button--next-{{ section.id }}"
              aria-controls="slider-button--next-{{ section.id }}">
              <span>{% render 'icon-caret' %}</span>
          </button>
          </div>
        {%- endif -%}
      </div>
     </slider-component>
    {% endif %}
  </div>
  {% endif %} 
  </product-recommendations>
</div>
{% javascript %}
  class ProductRecommendations extends HTMLElement {
    constructor() {
      super();

      const handleIntersection = (entries, observer) => {
        if (!entries[0].isIntersecting) return;
        observer.unobserve(this);

        fetch(this.dataset.url)
          .then(response => response.text())
          .then(text => {
            const html = document.createElement('div');
            html.innerHTML = text;
            const recommendations = html.querySelector('product-recommendations');
            if (recommendations && recommendations.innerHTML.trim().length) 
              this.innerHTML = recommendations.innerHTML;
            }
          })
          .catch(e => {
            console.error(e);
          });
      }

      new IntersectionObserver(handleIntersection.bind(this), {rootMargin: '0px 0px 200px 0px'}).observe(this);
    }
  }

  customElements.define('product-recommendations', ProductRecommendations);
{% endjavascript %}

Please help as soon as possible i need urgent help. Thanks!

What else do I need to do to have my custom WooCommerce Analytics filter applied to exports?

I’m working with WooCommerce Analytics, and have successfully added a dropdown to the orders and reports screens. The dropdown allows me to select whether or not to include subscription related orders in the data displayed on screen, and it works.

There is only limited information about extending WooCommerce Analytics found online, but all of them show only one place in JavaScript where a filter is used to add my dropdown to the page. I would think that by adding the dropdown to the page that WooCommerce would be smart enough to see the value it contains, and include the parameter in its request to do the export, but when I click on the “Download” button, the REST request only contains the built-in filter params that WooCommerce provides, it does not contain my custom param “subtype”.

{
    "report_args":{
        "orderby":"date",
        "order":"desc",
        "after":"2024-08-01T00:00:00",
        "before":"2024-08-26T23:59:59",
        "page":1,
        "per_page":25,
        "match":"all",
        "status_is":"completed",
        "extended_info":true
    },
    "email":true
}

You can see in that payload that WooCommerce added its own “status_is” parameter when I selected it. I want my “subtype” parameter to be added to the payload.

What else do I need to do to get the exports to match the on screen data? Here is the way I add the dropdown to the orders and revenue screens:

if(
    typeof wp !== 'undefined' &&
    typeof wp.hooks !== 'undefined' &&
    typeof wp.hooks.addFilter === 'function'
){
    // Orders screen
    wp.hooks.addFilter(
        'woocommerce_admin_orders_report_filters',
        'wass-wc-analytics-extension',
        ( originalFilters ) => {
            // Add the dropdown
            return [
                {
                    label: 'Subscription/Order Types',
                    staticParams: [],
                    param: 'subtype', // The query parameter that will be used
                    showFilters: () => true,
                    defaultValue: '1',
                    filters: [...(wcSettings.subtypes || [])]
                },
                ...originalFilters,
            ];
        }
    );

    // Revenue screen
    wp.hooks.addFilter(
        'woocommerce_admin_revenue_report_filters',
        'wass-wc-analytics-extension',
        ( originalFilters ) => {
            // Add the dropdown
            return [
                {
                    label: 'Subscription/Order Types',
                    staticParams: [],
                    param: 'subtype', // The query parameter that will be used
                    showFilters: () => true,
                    defaultValue: '1',
                    filters: [...(wcSettings.subtypes || [])]
                },
                ...originalFilters,
            ];
        }
    );
}

I can show more code if necessary, but I believe these are the relevant snippets needed.

How to Obtain clientId, tenantId, and clientSecret for Azure OpenAI Authentication in Production

I’m developing an application that uses Azure OpenAI, and I’m facing challenges with setting up authentication in a production environment. Locally, I’m able to authenticate successfully using DefaultAzureCredential after running az login, but I can’t use this method in production.

I understand that in a production environment, it’s better to use ClientSecretCredential from @azure/identity. However, I’m unsure how to obtain the necessary clientId, tenantId, and clientSecret required for this credential type.

Locally, this setup works fine with DefaultAzureCredential:

import { AzureOpenAI } from 'openai';
import { DefaultAzureCredential } from '@azure/identity';

const credential = new DefaultAzureCredential();
const deployment = 'gpt-4o';
const apiVersion = '2024-02-15-preview';

const openai = new AzureOpenAI({
  azureADTokenProvider: getBearerTokenProvider(
    credential,
    'https://cognitiveservices.azure.com/.default'
  ),
  deployment,
  apiVersion,
});

Questions:

  1. Where can I obtain the clientId, tenantId, and clientSecret required for ClientSecretCredential?

  2. Are there any best practices for securely storing and managing these credentials in a production environment?

    Environment:

    • Node.js v14.17.0

    • TypeScript v4.4.2

    • Azure OpenAI SDK (latest version)

    • @azure/identity (latest version)

What I Tried:

  • I reviewed the Azure documentation but found it unclear where to get these credentials specifically for use with Azure OpenAI.

  • I understand the concept of service principals but am unsure how to set one up correctly for this use case.

Any guidance or references would be greatly appreciated!

returning two arrays in one array that contain names with a certain letter and names without the stated letter

I’m doing for-loop practice and can only use for loops to iterate over the arrays and strings in the problems I’m working.
QUESTION:Return and array of 2 arrays
// (1 – an array of names that contain “a” in name, 2 – an array of names that don’t have ‘a’ in name)

I know how to push the names containing the letter ‘a’ to an array but the names that don’t contain the letter a, are being pushed into the array as many times as it’s being iterated over, how can I have the array of names that doesn’t contain the letter ‘a’ only contain the name once and not as many times as its iterated over I know the issue lies somewhere is me having the for loop nested I think but I just cant see it, any tips or advice are welcome !

const arr1 = ['susan', 'meghan', 'timmy', 'tommy', 'thomas'];

function itsSomething(array) {
  let bothArrays = [];
  let withA = [];
  let withoutA = [];
  for (let i = 0; i < array.length; i++) {
    let name = array[i];
    for (let x = 0; x < name.length; x++) {
      if (name[x] == 'a') {
        withA.push(name)
      } else {
        withoutA.push(name)
      }
    }
  }
  bothArrays.push(withA, withoutA);
  return bothArrays
}

console.log(itsSomething(arr1))

HTML Pattern Validation for Phone Number Always Passing Despite Incorrect Input [duplicate]

I’m working on a validation form where the phone number field should accept:

  • 10 digits in a row (e.g., 1234567890), or
  • A pattern of three digits, three digits, then four digits, separated by either spaces, dashes, or dots (e.g., 123-456-7890, 123.456.7890, 123 456 7890).
input:valid {
  background-color: lightblue;
}
<input type="text" pattern="^(d{10}|d{3}[-.s]d{3}[-.s]d{4})$" id="phone" required>

In my implementation, the input field’s text turns blue when valid, but it shows as valid no matter what characters or how many characters I type. Even invalid inputs like random letters or fewer than 10 digits still make the field appear valid.

  • I’ve tested the pattern in regex101: It works perfectly there, matching only the correct formats.
  • I’ve also tried other patterns in different browsers and all good.
  • I’ve tested in Firefox and Chrome.

Linear gradient in d3

I’m trying to create a conic gradient effect using the D3.js library, but I understand that conic gradients aren’t natively supported. My goal is to manually implement a clockwise gray gradient that moves along the rim of a circle, starting from the 12 o’clock position after the circle is rendered and finally turns the whole circle gray.

Actual vs desired results

From the point of view of the application, it is important that the animation starts after the rendering is finished, and also that the gradient runs as described, similar to a curved progress bar.

In this example you can see my progress so far.

How can I achieve a smooth, continuous gradient that transitions clockwise around the circle?

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D3 Circle Gradient</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<svg width="500" height="500"></svg>
<script>
const renderCircle = () => {

  const svg = d3.select("svg");
  svg.selectAll("*").remove();

  const margin = {
    top: 50,
    right: 50,
    bottom: 50,
    left: 50
  };

  const width = 500;
  const height = 500;
  const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);

  // Circle properties
  const cx = width / 2;
  const cy = height / 2;
  const radius = 0;
  const finalRadius = Math.min(width, height) / 4;
  const strokeWidth = 10;


  const gradientId = "linearGrad";
  const gradient = svg.append("defs")
    .append("linearGradient")
    .attr("id", gradientId)
    .attr("gradientUnits", "objectBoundingBox");


  gradient.append("stop")
    .attr("offset", "0%")
    .attr("stop-color", "red");

  gradient.append("stop")
    .attr("offset", "100%")
    .attr("stop-color", "gray");

  const circle = g.append("circle")
    .attr("cx", cx)
    .attr("cy", cy)
    .attr("r", radius)
    .attr("fill", "none")
    .attr("stroke", `url(#${gradientId})`)
    .attr("stroke-width", strokeWidth)
    .transition()
    .duration(100)
    .attr("r", finalRadius)
    .on("end", function() {


      let angle = 0;
      let step = 1;

      d3.interval(() => {
        angle += step;
        if (angle <= 360) {
          gradient
            .attr("x1", `50%`)
            .attr("y1", `50%`)

            .attr("x2", `${50 + Math.round((Math.sin(angle * Math.PI / 180) * finalRadius)/(2*finalRadius / 100))}%`)
            .attr("y2", `${Math.round((finalRadius - Math.cos(angle * Math.PI / 180)*finalRadius)/(2 * finalRadius / 100))}%`);
        };
      }, 10);
    });

};

renderCircle();
</script>
</body>
</html>

Thank you!

Filter out getByText elements that contain “disabled” class name

Have a calendar that might have a date displayed twice: from the previous month and for the current month:

enter image description here

The disabled dates have disabled in the class, like this:

<div role="gridcell" class="ngb-dp-day disabled" tabindex="-1" aria-label="Sunday, July 28, 2024">
<span _ngcontent-dug-c147="" class="custom-day weekend disabled"> 28 </span>
<!----><!---->
</div>

The active element does not have disabled in the class name

<div role="gridcell" class="ngb-dp-day" tabindex="-1" aria-label="Wednesday, August 28, 2024">
<span _ngcontent-dug-c147="" class="custom-day"> 28 </span>
<!----><!---->
</div>

In my current implementation I am using page.getByText("28", { exact: true }).click() but it fails because there are two elements with the same text.

How can I filter out the disabled one?

I was trying to use this, but it does not exactly work

await this.page.getByText("28")
    .filter({ hasNot: this.page.locator('span[class~="disabled"]').click()

Can selected Livewire properties be just sent from a component to its template (i.e. without two-way binding)?

I have a form in a Blade template that utilises Livewire:

{{-- resources/views/page-generation.blade.php --}}
<div class="py-12">
    <livewire:titlegen.form />
</div>

The form looks like this

<?php
// app/Livewire/Titlegen/Form.php

namespace AppLivewireTitlegen;

use LivewireComponent;

class Form extends Component
{
    // Two way (entered by user, but need to be reflected on screen when loading)
    public string $productName;
    public string $targetAudience;
    public string $usps;
    public string $cta;
    public string $keyPhrases;

    // Outputs (generated on server, shown to user)
    public ?array $titles;
    public ?string $ctaOut;
    public ?string $error;

    // Outputs (stored on server, shown to user)
    public array $menus = [
        // Long menu to render
    ];

    public function boot(ExampleDependency $dependency): void
    {
        // Set dependencies...
    }

    // Some Livewire action methods here...
}

The first two categories do require binding. The first group are two way, and although the second group are only one way, they are small, and it is not a great bother they are send in the wrong direction.

But the $menus is an interesting one. I want to set it in the Component class, and it is already exposed in the template as I want, but this means that it becomes treated as a bound property, so it will be send from the client back to the server. (I don’t want this to happen, as it is a waste of bandwidth, but moreover it unnecessarily complicates my server input filtering).

I suppose I can just set this in the template, but that feels a bit hacky. Is there a dynamic way I can pass PHP variables to the rendered template without them becoming bound in the two way process?

I’ve been reading about Wireables, and I suppose I could use that to collapse private data into a harmless null value. But that feels rather like a laborious hack, rather than a solution. Is there anything better?

How to serve static HTML file with react-router-dom [duplicate]

I am linking my website to authorize.net’s payment gateway by embedding their payment form in my site via an IFrame. As part of their requirements for this to work, they give me a file “IFrameCommunicator.html” which MUST be hosted on the same domain as the site with the IFrame to receive its response.

My site is set up in React using react-router-dom for page routing, which requires all routes to be React components, so I’m not sure how to set up a URL that routes to this file.

My router looks like this:

const router = createBrowserRouter([
  {
    path: "/",
    element: <RootPage/>,
    errorElement: <ErrorPage/>,
    children:[
      {
        path: "purchase",
        element: <CreditPurchase/>,
      },
      {
        path: "receipt",
        element: <PaymentReceiptPage/>,
      },
    ]
  },
  {
    path:"iframeCommunicator.html",
    //how to link to static html rather than react comp?

  }
  
]);

and IFrameCommunicator.html is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Iframe Communicator</title>
    <script type="text/javascript">
        //<![CDATA[
            function callParentFunction(str) {
                if (str && str.length > 0 
                    && window.parent 
                    && window.parent.parent
                    && window.parent.parent.AuthorizeNetIFrame 
                    && window.parent.parent.AuthorizeNetIFrame.onReceiveCommunication)
                    {
// Errors indicate a mismatch in domain between the page containing the iframe and this page.
                        window.parent.parent.AuthorizeNetIFrame.onReceiveCommunication(str);
                    }
                }

            function receiveMessage(event) {
                if (event && event.data) {
                    callParentFunction(event.data);
                    }
                }

                if (window.addEventListener) {
                    window.addEventListener("message", receiveMessage, false);
                    } else if (window.attachEvent) {
                        window.attachEvent("onmessage", receiveMessage);
                    }

                if (window.location.hash && window.location.hash.length > 1) {
                    callParentFunction(window.location.hash.substring(1));
                    }
        //]]/>
    </script>
</head>
<body>
</body>
</html>

How can I make it so that mysiteurl/IFrameCommunicator.html actually links to the file “IFrameCommunicator.html”. I can’t export it as a React component since this results in the entire file being placed in the HTML body of my site, which doesn’t work. I can’t see any way to make this work with react-router-dom, so is there another way to serve this HTML file on the same domain as my react site?

How to group columns in a datatable: Using nested tables or colspan?

I have a datatable in my web application, and I need to group a set of columns under a single header. I am trying to determine the best practice for achieving this.

Here are the two approaches I am considering:

  1. Using colspan: This seems straightforward and keeps the HTML structure simple. However, I am concerned about how it will scale with more complex data structures and if there are any limitations.

  2. Using nested tables: This approach might provide more flexibility for complex groupings, but I am worried it could make the code harder to maintain and affect accessibility.

Which method is considered a best practice for grouping columns in a datatable? Are there any specific pros and cons of using colspan versus nested tables that I should be aware of?

Is there a better way to structure my datatable for accessibility and maintainability?

Chrome Memory footprint creeps to 3.554 GB though JS heap memory is at 20 MB

My application consists of a table that receives and displays live data for long periods of time and hence continuously creates and destroys table rows in the DOM.

What I have noticed is that there is a creep in memory consumed by the application. Though the heap memory rose from 8.6 MB to 20 MB, the browser’s memory footprint on Chrome Task manager (or Committed bytes on Windows Performance Monitor) increased to 3.55 GB and keeps moving up gradually. This is ultimately leading to a browser crash.

From the heap I see that the % of Strings kept rising and went up to 49%. Beyond that, I wasn’t able to create a heap dump, possibly due to the large memory footprint.

Question: Should I try still try to optimize the Heap? I could not understand why the browser would need to commit 3 GB+ when the Heap is only 20 MB in size and ultimately crash.

enter image description here

I had cleared some previous leaks by setting references to null and optimizing closures from arrow functions. But the browser footprint seems huge in comparison with the heap size. That makes me wonder if I am going in the right direction.

Seeing this in both Edge and Chrome browsers.

Why is content showing null for cell data in each row while headers render correctly using Tanstack Table and ShadCN in Next.js?

I’m working on a data table in a Next.js project where I’m using Tanstack Table to manage the data and ShadCN for table formatting. The table headers are rendering correctly, but when I try to render the data in each cell, the contents of consistently show null. I’ve attempted to troubleshoot by console logging the cell content, but it still shows null.

Here is the code I’m working with:

Data file (./data/data.js):

export const rewardsData = {
  columns: [
    { header: "ID", id: "id" },
    { header: "Full Name", id: "fullName" },
    { header: "Email", id: "email" },
    { header: "Campaign Name", id: "campaignName" },
    { header: "Review Posted", id: "reviewPosted" },
    { header: "Status", id: "status" },
  ],
  rows: [
    {
      id: 1,
      fullName: "Morlee Tapson",
      email: "[email protected]",
      campaignName: "ligula suspendisse ornare",
      reviewPosted: "2024-01-08T16:14:24Z",
      status: true,
    },
    {
      id: 2,
      fullName: "Trixi Verrechia",
      email: "[email protected]",
      campaignName: "quisque erat eros viverra eget",
      reviewPosted: "2024-03-23T12:07:09Z",
      status: false,
    },
    // more data here    
  ],
};

Reusable Table Component (./components/ReusableTable.jsx):

import {
  Table,
  TableCaption,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
} from "@/components/ui/table";
import {
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";
import Link from "next/link";

export default function ReusableTable({
  data,
  captionLink = "",
  captionText = "",
}) {
  const { columns, rows } = data;

  const table = useReactTable({
    columns: columns,
    data: rows,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <Table className="mt-5">
      {captionText && (
        <TableCaption className="text-left">
          {captionLink ? (
            <Link href={captionLink}>{captionText}</Link>
          ) : (
            captionText
          )}
        </TableCaption>
      )}
      <TableHeader>
        {table.getHeaderGroups().map((headerGroup) => (
          <TableRow key={headerGroup.id}>
            {headerGroup.headers.map((header) => {
              const headerContent = flexRender(
                header.column.columnDef.header,
                header.getContext()
              );
              return <TableHead key={header.id}>{headerContent}</TableHead>;
            })}
          </TableRow>
        ))}
      </TableHeader>
      <TableBody>
        {table.getRowModel().rows?.length ? (
          table.getRowModel().rows.map((row) => (
            <TableRow key={row.id}>
              {row.getVisibleCells().map((cell) => {
                const cellContent = flexRender(
                  row.original[cell.column.id], // Issue might be here
                  cell.getContext()
                );
                return (
                  <TableCell key={cell.id}>
                    {console.log(cellContent) /* Returns null */}
                    {cellContent}
                  </TableCell>
                );
              })}
            </TableRow>
          ))
        ) : (
          <TableRow>
            <TableCell colSpan={table.columns.length}>
              No data available
            </TableCell>
          </TableRow>
        )}
      </TableBody>
    </Table>
  );
}

Usage in a Page (./app/table/page.jsx):

import ReusableTable from "@/components/ReusableTable";
import { rewardsData } from "@/data/rewardsData";

export default function Page() {
  return (
    <>
      <div className="mt-8">
        <h2 className="font-extrabold text-xl">Customer List</h2>
      </div>
      <div>
        {rewardsData ? (
          <ReusableTable
            data={rewardsData}
            captionLink="/rewards-center"
            captionText="View More"
          />
        ) : (
          <p>No data available</p>
        )}
      </div>
    </>
  );
}

Problem:
The table headers are displaying as expected, but the content within each cell is not rendering, and the contents in show null when I log the output. The headers map correctly, but cell data fails to appear.

How to select all rows in Supabase?

I have a table named ‘locations’ and I am trying to fetch all records.

Here’s a snippet of my code

const { data, error } = await supabase
    .from('locations')
    .select(*)
    .order('country', { ascending: true })
    .order('state', { ascending: true })

I have over 25000 rows with all 50 US states, and I only get 3 of the States to return.

I even tried to increase the limit:

const { data, error } = await supabase
    .from('locations')
    .select(*)
    .order('country', { ascending: true })
    .order('state', { ascending: true })
    .limit(25000)

That didn’t work.

Svelte prerender with ‘dynamic’ route

I am trying to use svelte SSG because all of my data is fetched from an external API. All of my routes are being generated except for one route because it has parameters. It looks something like this:

“/user/[userId]/code/[code]”

That route is used as email verification. It isn’t accessed anywhere in the code because the server sends an email. However, because of the parameters (and I guess because the route is not elsewhere in the code) it will not generate a proper route for that.

I tried putting two examples in ‘svelte.config.js’ in ‘kit.prerender.entries’ but it just creates two routes that exactly match the userId and code.

The JS in the page just gets the data from the URL, takes some user input and then makes a fetch request, so it can be prerendered.

Is there any way to have dynamic routes such as this in Svelte SSG or is that just impossible?

How to properly escape payloads sent with URLFetchApp when the payload contains double quotes

I am trying to POST a payload to a CMS using URLFetchApp. The payload has quotes in the text. I am using URLFetchApp because the code is executing inside a Google Apps Script, which from what I understand does not support libraries like request or https.

This is the payload, which matches the specifications of the CMS’s API documentation (and which I have successfully POSTed to the CMS using Node libraries):

{"content":"<?xml version="1.0"?><section xmlns="http://docbook.org/ns/docbook" xmlns:xinfo="http://ns.expertinfo.se/cms/xmlns/1.0" xml:id="12345" version="5.0" xml:lang="en" xinfo:resource="12345" xinfo:resource-id="1234" xinfo:resource-type="component" xinfo:resource-title="Source 5" xinfo:resource-titlelabel="" xinfo:version-major="1" xinfo:version-minor="0">  <title xinfo:text="1234">Name</title>  <para>Short overview</para></section>"}

Then I run this code…

var data = {
"content": finalContent
 }
payload = JSON.stringify(data);

…which produces the payload variable equaling this string, which is single escaped:

{"content":"<?xml version="1.0"?><section xmlns="http://docbook.org/ns/docbook" xmlns:xinfo="http://ns.expertinfo.se/cms/xmlns/1.0" xml:id="12345" version="5.0" xml:lang="en" xinfo:resource="12345" xinfo:resource-id="1234" xinfo:resource-type="component" xinfo:resource-title="Source 5" xinfo:resource-titlelabel="" xinfo:version-major="1" xinfo:version-minor="0">  <title xinfo:text="1234">Name</title>  <para>Short overview</para></section>"}

Then I plug the payload variable into the URLFetchApp code:

const url = "https://<the CMS>.com/api/v2/documents/1234";
const params = {
  headers: {
    Authorization: "Basic <token>",
    accept: "application/json",
  },
  method: "put",
  payload: payload,
  contentType: "application/json"
};
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText());

But according to the logs, the payload URLFetchApp sends this string that is double escaped:

{"content":"<?xml version=\"1.0\"?><section xmlns=\"http://docbook.org/ns/docbook\" xmlns:xinfo=\"http://ns.expertinfo.se/cms/xmlns/1.0\" xml:id=\"12345\" version=\"5.0\" xml:lang=\"en\" xinfo:resource=\"12345\" xinfo:resource-id=\"1234\" xinfo:resource-type=\"component\" xinfo:resource-title=\"Source 5\" xinfo:resource-titlelabel=\"\" xinfo:version-major=\"1\" xinfo:version-minor=\"0\">  <title xinfo:text=\"1234\">Name</title>  <para>Short overview</para></section>"}

The CMS continually throws this error:

{"error":{"code":422,"type":"unprocessable_entity","message":"Text not allowed in DocBook element u201clistitemu201d in this context."}}

I assume the error message is referring to this part of the string and possibly the second backslash at the end: xmlns=\"http://docbook.org/ns/docbook\"

But when I send the payload through URLFetchApp without stringifying it, nothing is escaped. This is the payload sent by URLFetchApp:

{"content":"<?xml version="1.0"?><section xmlns="http://docbook.org/ns/docbook" xmlns:xinfo="http://ns.expertinfo.se/cms/xmlns/1.0" xml:id="12345" version="5.0" xml:lang="en" xinfo:resource="12345" xinfo:resource-id="1234" xinfo:resource-type="component" xinfo:resource-title="Source 5" xinfo:resource-titlelabel="" xinfo:version-major="1" xinfo:version-minor="0">  <title xinfo:text="1234">Name</title>  <para>Short overview</para></section>"}

This is the error returned by the CMS:

{"error":{"code":400,"type":"bad_request","message":"Invalid body."}}

I have tried:

  • Constructing payloads with single quotes around the key and value pair
  • Constructing payloads that include the content key
  • Constructing payloads that nest the content key under payload in the request
  • All kinds of combinations of single quotes, double quotes, and escaped quotes, and different kinds of encoding

All fail with one of the two errors included above.

Is it possible to send a payload through URLFetchApp with only one escape per quote?

Thank you for any help and patience as I am not a programmer by profession.