escape characters must be escapped & unable to find the error

i am getting “%20” error when i run some softwares
tried to figure out the issue, it seem to be with this code.
im getting an error “escape characters must be escaped” but cant figure out what to do next

please asisst me fixing this line of code:

<a class="megamenu-item cruise-departure-item" href="{{ jet_engine_url(args={}) }}">
    {% if jet_engine_show_if(args={"jedv_condition":"exists","jedv_field":"departure-image","jedv_context":"current_listing"}) %}
    <img class="megamenu-item__img" src="{{ jet_engine_data(args={source:'meta',meta_key:'departure-image'}) |jet_engine_callback(args={cb:'wp_get_attachment_image',attachment_image_size:'medium'}) }}
    {% endif %}
    {% if jet_engine_show_if(args={"jedv_condition":"not-exists","jedv_field":"departure-image","jedv_context":"current_listing"}) %}
    <img class="megamenu-item__img" src="/wp-content/uploads/2024/05/v3.jpg">
    {% endif %}
    <p class="megamenu-item__title">
        {{ jet_engine_data(args={key:'name'}) }}
    </p>
</a>

sharing also an image with the error

enter image description here

react-chartjs-2 chartref update doesn’t work

This is my script of React component,

It dosen’t show the label, however dataset is correct,

So I guess this is the problem of update?

I really appreciate any hint,

import React,{useRef,useState,useEffect} from 'react'
import axios from 'axios';
import styles from "../css/test-styles.module.css";
import { Line } from 'react-chartjs-2';


import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend,
  } from 'chart.js'

ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
)


const DashboardPage = (props) =>{

    const data = useRef();
    const chartRef = useRef();
    const [labels,setLabels] = useState([]);
    const options = {
        responsive: true,
        plugins: {
          legend: {
            position: 'top'
          },
          title: {
            display: true,
            text: 'Chart.js Line Chart',
          },
        },
      };

    useEffect(()=>{
     

        data.current = {
            //labels:["june","july","august"],
            labels:labels,
            datasets: [
                {
                label: 'Dataset 1',
                data: [100,200,300],
                borderColor: 'rgb(255, 99, 132)',
                backgroundColor: 'rgba(255, 99, 132, 0.5)',
                },
                {
                label: 'Dataset 2',
                data: [350,150,250,100,200],
                borderColor: 'rgb(53, 162, 235)',
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                },
            ],
        };
        console.log("data",data.current); //data is correctly set
        console.log("chartref",chartRef);

        chartRef.current?.update();// it not work??
    },[labels])

    useEffect(()=>{
        const now = new Date();
        const OLDEST_DATE = new Date(2025, 0, 3)
        const resultDates = [];
        for (let date = OLDEST_DATE; date <= now; date.setDate(date.getDate() + 1)) {
            resultDates.push(new Date(date));
        }
        console.log(resultDates);
        var arr = resultDates.map((d)=>{
            return d.getMonth().toString() + "/" + d.getDate().toString();
        })
        console.log(arr);
        setLabels(arr);
    },[])
    return (
        <div className={styles.wrapper} style={{padding:"10px"}}>
            {data.current && 
            <Line ref={chartRef} options={options} data={data.current}/>}

        </div>

    );    
}

export default DashboardPage;

Why is my spotify redirect_uri query parameter changing?

In the code of my website, which is hosted on Github Pages, my redirect_uri is set to my production URL, which I have listed in the app’s settings on Spotify’s website. However, when I load the website, the redirect_uri query parameter changes to a localhost URL, even though it is supposed to be the production URL. Any reasons this could be happening?

How to implement dual hover for desktop and tap feedback for touch devices in a React hamburger menu?

I’m working on a responsive navigation component using React and SCSS. My goal is to have a hover effect on desktop when a user hovers over the hamburger icon and a tap effect on mobile devices where the lines turn gold on tap (and stay gold for .3 seconds after tap)

SCSS code

.hamburger {
display: none;
flex-direction: column;
justify-content: space-between;
width: 24px;
height: 18px;
cursor: pointer;
z-index: 101;

.line {
  height: 3px;
  background: $white;
  border-radius: 2px;
  transition: background-color 0.3s ease;
}

&:active .line, &.active .line {
  background-color: $dark-gold;
  transition: background-color 0.3s ease;
}

@media (hover: hover) and (pointer: fine) {
  &:hover .line {
    background-color: $dark-gold;
  }
}

}

React component

import { React, useState } from 'react'

import { Link } from ‘react-router-dom’;

const Header = () => {
const [menuOpen, setMenuOpen] = useState(false)

const toggleMenu = () => {
    setMenuOpen((prev) => !prev)
}

const closeMenu = () => {
    setMenuOpen(false)
}

return (
    <header className="header">
        <Link to="/">
            <img src="./img" 
                alt="Company Logo" 
                className="logo"
            />
        </Link>
        <nav className={`nav-menu ${menuOpen ? 'open' : ''}`}>
            <Link to="/" className='nav-item' onClick={closeMenu}>Home</Link>
            <Link to="/about" className='nav-item' onClick={closeMenu}>About Us</Link>
            <a href="#" className="nav-item" onClick={closeMenu}>Products</a>
            <Link to="/mc-cares" className='nav-item' onClick={closeMenu}>MC Cares</Link>
            <Link to="/faqs" className='nav-item' onClick={closeMenu}>FAQs</Link>
        </nav>
        <div className="hamburger" onClick={toggleMenu}>
            <div className="line"></div>
            <div className="line"></div>
            <div className="line"></div>
        </div>
    </header>
);

};

export default Header

The desktop hover effect works perfectly. It’s the tap that isn’t working.

Do you know is there a better way to handle this dual action (hover for desktop + tap for mobile) with React and SCSS?

onClick button doesnt work in my project with Next.js 15.1.3 version

I have a problem in my project that the onClick property on the button tag does not run even though my code is also not an error my debugging also has no changes, I am using next js version 15 and here is my code

NavLink.jsx

import Link from "next/link";

export default function NavLink({ children, url, addClass = "" }) {
  return (
    <li>
      <Link
        href={url}
        className={`block py-2 px-3 rounded ${addClass}`}
      >
        {children}
      </Link>
    </li>
  );
}

index.jsx

"use client";
import { useState } from "react";
import { routes } from "@/routes";
import NavLink from "./NavLink";

export default function Navigation() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
    console.log('Menu is open:', isMenuOpen);
  };

  return (
    <nav
      className={`section-padding-x fixed top-0 w-full z-[998] text-dark-base normal-font-size transition-all duration-300 bg-light-base shadow-md`}
    >
      <div className="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto xl:px-0 py-4">
        <a href="#" className="flex items-center space-x-3 rtl:space-x-reverse">
          <img src="/favicon.png" className="h-8" alt="DevFlex Logo" />
          <span className="self-center text-2xl font-semibold whitespace-nowrap">
            Jack's
          </span>
        </a>
        <button
          type="button"
          className="lg:hidden text-dark-base relative z-[999] focus:outline-none"
          onClick={toggleMenu}
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="currentColor"
            className="w-8"
            viewBox="0 0 448 512"
          >
            <path d="M0 96C0 78.3 14.3 64 32 64l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 128C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 288c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32L32 448c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z" />
          </svg>
        </button>
        <div
          className={`w-full lg:block lg:w-auto ${
            isMenuOpen ? "block" : "hidden"
          }`}
        >
          <ul className="font-medium flex flex-col p-4 lg:p-0 mt-4 border rounded-lg lg:flex-row rtl:space-x-reverse lg:mt-0 lg:border-0 gap-2 lg:gap-0">
            {routes.map((route, index) => (
              <NavLink key={index} url={route.url}>
                {route.title}
              </NavLink>
            ))}
          </ul>
        </div>
      </div>
    </nav>
  );
}

I tried so much such as debugging but the result is none

Octal escape sequences are not allowed:

const str = `        Name: FirstName LastName
        123-45-6789
        987-65-4321
        Address: 1234 abc Street, Apt. 567, Ricefield, ILE 602701
        Phone: (123) 456-7890
        t
        Email: [email protected]
        URL: https://www.example.com
        f 
        IP: 192.168.1.1
        Date: 01/01/2023
        Price: $99.99
        r 
        Color: Red, Blue, Green, Yellow
        Mixed: abc123XYZ987
         v
        141pple x42anana u0063herry
        
`;
 let regexOctal = /141/;
 console.log("regexOctal.exec(str) : ", regexOctal.exec(str));

error at : 141pple

i wanted to see how octal , hex and unicode is worked with regex to search

i tried using ${} in Template Strings and also in new variable without Template Strings but still error
1)

const str = `        Name: FirstName LastName
        123-45-6789
        987-65-4321
        Address: 1234 abc Street, Apt. 567, Ricefield, ILE 602701
        Phone: (123) 456-7890
        t
        Email: [email protected]
        URL: https://www.example.com
        f 
        IP: 192.168.1.1
        Date: 01/01/2023
        Price: $99.99
        r 
        Color: Red, Blue, Green, Yellow
        Mixed: abc123XYZ987
         v
        ${"141"}pple x42anana u0063herry
`;

2)const newStr = "141pple x42anana u0063herry";

How to add color block on mat-select value?

enter image description here

I am using mat-select in my Angular project to display dropdown values. The dropdown options include three values: shiftCode, shiftStartTime, and shiftEndTime. These values are combined and displayed in the dropdown list. However, after a selection is made, I want to display only the shiftCode in the placeholder along with a color block that corresponds to a colorAssigned variable from the dropdown option.

Here is my current code:

<ng-container>
  <span 
    class="font-weight-bold" 
    [style.color]="this.calendarGrid[j][p].disable ? '#cbcccb' : null">
    {{ this.calendarGrid[j][p].date }}
  </span>
  <mat-select 
    [(value)]="this.calendarGrid[j][p].dropdownValue"
    (openedChange)="onDropdownToggle($event)"
    [pTooltip]="tooltipContent"
    tooltipPosition="bottom"
    [panelClass]="'custom-select-panel'"
    class="mat-select-custom-width-dropdown"
    (selectionChange)="onGridSelectionChange($event, j, p)"
    [disabled]="this.calendarGrid[j][p].disable"
    [ngClass]="this.calendarGrid[j][p].disable ? 'search_select-week' : ''"
    class="search_select_shift custom_placeholder w-100"
    placeholder="Select">

    <div class="mat_search">
      <div class="search-icon">
        <input type="text" name="filter-options" class="input_search" placeholder="Type...">
        <img src="assets/img/search-icon.svg" alt="search-icon">
      </div>
      <mat-option [value]="">Select</mat-option>
      <mat-option [value]="'A'">Weekly Off</mat-option>
      <mat-option *ngFor="let option of shiftDropDownList" [value]="option.shiftCode" class="d-flex align-items-center">
        {{ option.shiftCode + ' | ' + option.shiftStartTime + '-' + option.shiftEndTime }}
      </mat-option>
    </div>
  </mat-select>
</ng-container>

In this particular code I am using mat-select in which i am showing the dropdown values , the dropdown value contains three values (shiftCode ,shiftStartTime,shiftEndTime) which is showing combined in the dropdown list but after the selection I want to show just only shiftCode with the color assigned on the block as shown in image.

Here In the dropdown array, I have a colorAssigned variable in the option (which i can be used like option.colorAssigned that gives result ‘#fff‘)

cookie’s value becomes null after a while

I store the access token and refresh token in separate cookies, with both set to expire after 7 days. The access token itself expires every 10 minutes. I’ve implemented a refresh token function that runs 1 minute before the access token expires, automatically updating the token state. The tokens remain valid while actively using the website, but if I become idle for some time, the access token value becomes null.

`"use client";
import { createContext, useContext, useState, useEffect } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import jwt from "jsonwebtoken";
import { useRouter } from "next/navigation";

const AuthContext = createContext();

export const AuthProvider = ({ 
children
 }) => {
  const apiURL = process.env.NEXT_PUBLIC_API_URL;
  const router = useRouter();

  const [user, setUser] = useState(null);
  const [token, setToken] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const storedToken = Cookies.get("token");
    if (storedToken) {
      setToken(storedToken);
    } else {
      logoutAction();
    }
  }, []);

  useEffect(() => {
    const storedUser = JSON.parse(localStorage.getItem("user"));

    if (storedUser) {
      if (storedUser.roleTypeId === 3) {
        router.push("/dashboard");
      }
    }
  }, [user]);

  useEffect(() => {
    const initializeAuth = async () => {
      setLoading(true);
      console.log(token);
      try {
        const storedUser = localStorage.getItem("user");
        if (storedUser) setUser(JSON.parse(storedUser));

        const currentToken = Cookies.get("token");
        console.log(currentToken);
        if (currentToken) {
          const decodedToken = jwt.decode(currentToken);
          if (Date.now() >= decodedToken?.exp * 1000) {
            await handleTokenRefresh();
          }
        } else {
          logoutAction();
        }
      } catch (error) {
        console.error("Error during auth initialization:", error);
      } finally {
        setLoading(false);
      }
    };

    initializeAuth();
  }, [token]);

  useEffect(() => {
    const intervalId = setInterval(async () => {
      try {
        if (token) {
          const decodedToken = jwt.decode(token);

          if (Date.now() >= decodedToken?.exp * 1000) {
            await handleTokenRefresh();
          }
        }
      } catch (error) {
        throw error;
      }
    }, 60000);

    return () => {
      clearInterval(intervalId);
    };
  });

  const handleTokenRefresh = async () => {
    try {
      const currentRefreshToken = Cookies.get("refreshToken");
      const currentToken = Cookies.get("token");

      const { data } = await axios.post(
        `${apiURL}/Authentication/RefreshToken`,
        {
          refreshToken: currentRefreshToken,
          token: currentToken,
        },
        {
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
            Authorization: `bearer ${token}`,
          },
        }
      );

      updateTokens(data.token, data.refreshToken);
      return data;
    } catch (error) {
      console.error("Error refreshing token:", error);
      logoutAction();
      throw error;
    }
  };

  const updateTokens = (
newToken
, newRefreshToken) => {
    const cookieOptions = {
      secure: true,
      sameSite: "strict",
      expires: 7,
      path: "/",
      domain: window.location.hostname,
    };

    Cookies.set("token", 
newToken
, cookieOptions);
    Cookies.set("refreshToken", 
newRefreshToken
, cookieOptions);
    setToken(
newToken
);
  };

  const LoginAction = async (
loginData
) => {
    setLoading(true);
    try {
      const { data } = await axios.post(
        `${apiURL}/Authentication/LoginUser`,
        
loginData
,
        {
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
          },
        }
      );

      updateTokens(
        data.authenticationResult.token,
        data.authenticationResult.refreshToken
      );

      localStorage.setItem("user", JSON.stringify(data.user));
      setUser(data.user);
      return data;
    } catch (error) {
      throw error.response;
    } finally {
      setLoading(false);
    }
  };

  const logoutAction = () => {
    Cookies.remove("token");
    Cookies.remove("refreshToken");
    localStorage.removeItem("user");
    setUser(null);
    setToken(null);
    router.push("/");
  };

  return (
    <AuthContext.Provider 
value
={{ LoginAction, logoutAction, user, loading }}>
      {
children
}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);`

Can I bind x-transition in alpine.js like :x-transition:leave-end?

Can I use Alpine.js to set a variable within x-data and bind my animation effects based on the swipe direction? Currently, it doesn’t work when I try to do it this way.

:x-transition:leave-end="leaveEndClass"

Below is the logic for my actions

 handleTouchEnd() {
        if (!this.isSwiping) return;
        this.isSwiping = false;

        const touchEndTime = Date.now();
        const timeDiff = touchEndTime - this.touchStartTime;
        const horizontalSwipe = this.swipeEndX - this.swipeStartX;
        const verticalSwipe = this.swipeEndY - this.swipeStartY;

      
        if (timeDiff < 150 || Math.abs(horizontalSwipe) < 50 || Math.abs(verticalSwipe) > Math.abs(horizontalSwipe)) {
            return;
        }
        if (horizontalSwipe > 0) {
            this.leaveEndClass = 'opacity-0 translate-x-full';
            this.setTabIndex(Math.max(this.tabIndex - 1, 1));
        } else if (horizontalSwipe < 0) {
            this.leaveEndClass = 'opacity-0 -translate-x-full';
            this.setTabIndex(Math.min(this.tabIndex + 1, 3));
        }
    },

sorry my english is not very good

Currently, the way I wrote it doesn’t work. I also tried using a ternary condition, but it didn’t work either. I want to determine the swipe direction to make my animation slide either to the right or to the left.

What are the module types supported by the import statement in a browser?

I’ve read through this documentation on MDN regarding the import statement available for JS modules:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with

Both of the pages above give JSON and CSS as examples of additional resource types that can be loaded with the import statement:

import data from "https://example.com/data.json" with { type: "json" };
import styles from "https://example.com/styles.css" with { type: "css" };

However, they both also hint at there being more types, or at least they’re a bit non-committal about it:

“To import JSON, CSS, or other types of resource…”

“The type attribute also supports other module types.”

What are all of the import types could I reasonably expect to be supported in a browser?

How to remove a break before and after a copyToClipboard fuction

This is my first time posting on this forum, but I have lurked around for fun for years now. Anyway, I’m making a very simple tool, and needed some help. I’ve been on hiatus from coding for a very long time, so please forgive my formatting and likely horrible excess code. The issue I’m experiencing is when I put in the text in #1, then select a site on #2 which joins the two fields together, and finally select the copy and reset on #3 it works fine. The issue is, it adds a break before and a break after the generated URL. I’ve tried countless different ways to prevent them in order to just copy the joined URL only, but my skills just aren’t up to snuff. I’m sure it’s a simple fix for most if not all on this site, so thanks in advance!

Additionally, if anyone has any ideas how to cut down on anything else to make it more efficient and simple I’m open ears.

Thanks!

<!DOCTYPE html>
<html>
<head>
<style>

input[type=text]
{
    width: 100%;
    font-size: 15px;
    padding: 10px;
    margin: 0px;
    box-sizing: border-box;
    background-color: #D5DBDB;
    border: 2px solid #232F3E;
    border-radius: 5px;
}

.button
{
    border-radius: 5px;
    background-color: #D5DBDB;
    border: 2px solid #232F3E;
    color: black;
    text-aline: center;
    font-size: 15px;
    padding: 10px;
    width: 150px;
    transition: all 0.3s;
    cursor: pointer;
    margin: 5px;
}

.button:hover
{
    background-color: #232F3E;
    border: 2px solid #FF9900;
    color: white;
}

.button:focus
{
    background-color: #FF9900;
    color: black;
}

p
{
    border-left: 10px solid red;
    background-color: #D5DBDB;
    border-radius: 5px;
    text-indent: 5px;
    font-size: 12.5px;
    width: 100%;
}

div
{
    text-align: right;
}

</style>
</head>
<body>

<font size="3"><b>1:</b> Input field for XXXXXXX:</font><br><br>
<input type="text" id="testurlinput" placeholder="never provide XXXXXXX to XXXXXXX">
<br><br><hr><br>

<font size="3"><b>2:</b> Select the site:</font><br><br>
<button class="button" onclick="myFunction('http://www.google.com/')">Google</button>
<button class="button" onclick="myFunction('http://x.com/')">X (<i>Twitter</i>)</button>
<button class="button" onclick="myFunction('http://www.facebook.com/')">Facebook</button>
<button class="button" onclick="myFunction('http://www.instagram.com/')">Instagram</button>
<button class="button" onclick="myFunction('https://bsky.app/')">Bluesky</button><br>
<hr><br>

<font size="3"><b>3:</b> Provide XXXXXXX with the following XXXXXXX:</font>
<p id="testlink"></p>
<button class="button" onclick="copyToClipboard('testlink')">Copy Link &<br>Reset Page</button>
<br><br><hr><br>

<hr>

<script>
function myFunction(a)
{
    var z = document.getElementById("testurlinput").value;
    document.getElementById("testlink").innerHTML = a + z;
}
</script>

<script>
function copyToClipboard(id)
{
    var from = document.getElementById(id);
    var range = document.createRange();
    window.getSelection().removeAllRanges();
    range.selectNode(from);
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    window.location.reload();
}
</script>
</body>
</html>

The goal is simply to address both the breaks in the beginning and after in order to come out with a clean URL. As for what I’ve tried, I’ve already tried multiple different function formats to no avail.

Prior to submitting, I even reviewed more under the “Review questions already on Stack Overflow to see if your question is a duplicate.” section. Still nothing.

React project was not running on a server (On “npm start” command)

Cannot find module ‘ajv/dist/compile/codegen’
Require stack:

  • C:UsersDellDesktopmern-appmy-appnode_modulesajv-keywordsdistdefinitionstypeof.js
  • C:UsersDellDesktopmern-appmy-appnode_modulesajv-keywordsdistkeywordstypeof.js
  • C:UsersDellDesktopmern-appmy-appnode_modulesajv-keywordsdistkeywordsindex.js
  • C:UsersDellDesktopmern-appmy-appnode_modulesajv-keywordsdistindex.js
  • C:UsersDellDesktopmern-appmy-appnode_modulesschema-utilsdistvalidate.js
  • C:UsersDellDesktopmern-appmy-appnode_modulesschema-utilsdistindex.js
  • C:UsersDellDesktopmern-appmy-appnode_moduleswebpack-dev-serverlibServer.js
  • C:UsersDellDesktopmern-appmy-appnode_modulesreact-scriptsscriptsstart.js

How to rectify this ?

Maintain Timezone Information from `Date()` when calling `Date().toString()` in Javascript

I am trying to pass the user’s local time to my backend. Any calls to instances of Date() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) seem to lose the timezone information, inhibiting me from determining the user’s local time.

console.log('Local Time:', new Date().toString());
console.log('Local Time:', new Date());

Outputs:

Local Time: Wed Jan 08 2025 03:48:49 GMT (Coordinated Universal Time)
Local Time: Tue Jan 07 2025 22:48:49 GMT-0500 (Eastern Standard Time)

I am finding the same issue with other instance methods of Date().

Obtain reference to SignaturePad instance after creation

I have code that generates multiple signature pads on a page, giving them a unique ID along the way. I would like to be able to do individual signaturePad.toDataURL() calls as I process a button click, by looping through the canvas elements. I would also like to do single signaturePad.clear() functions as required.

I haven’t been able to figure out how to refer to the signature-pad instance that is attached to a given canvas element.

For clearing the signature, I’ve tried

$jq("body").on("click", ".signature-clear", function() {
 var canvas = document.getElementById($jq(this).closest('.canvas-wrap').find('canvas').attr('id'));
 var signaturePad = canvas.signaturePad();
});

But despite the canvas element being correctly targeted, I get the canvas.signaturePad is not a function error.

I’m sure it will be simple

Why does my nextToken work unless a filter is added to my graphql call?

Some context is needed for my question at the bottom of the post. There are two tables in the DynamoDB with the following schema.

type Post @model {
  id: ID!
  author: String!
  comments: [Comment] @hasMany
}

type Comment @model {
  id: ID!
  description: String!
  post: Post! @belongsTo
}

The Post table has 125 posts. The Comment table has 3000+ comments. Fetching all 125 Posts takes less than 5 seconds. Fetching all 3000+ comments with a limit of 1000 and paginating takes more than 10 seconds.

In each Post object, it contains a limit of 100 comments. Assuming each Post has 100+ comments, when we fetch all 125 posts, we have 1,250 of 3000+ comments within 5 seconds versus waiting greater than 10 seconds when we fetch all comments from the Comment table.

Code for fetching from Comment Table where it takes greater than 10 seconds.

    do {
      const result = await API.graphql(graphqlOperation(listComments, { limit: 1000, nextToken }));
      const tokens = result.data.listComments.items;
      allEvents.push(...tokens);
      nextToken = result.data.listComments.nextToken;
    } while (nextToken);

In order to speed up the time it takes for our app to get all the comments (the goal), I tried extracting all comment data from the Post objects since we get all Post objects much faster. The thinking was if we get 1250 comments from the Posts that quickly, we could just take the nextToken from the Post.comments.nextToken. (array of 100 comments is at Post.comments.items), and hit that same graphql function above. However when doing that, it returns the following pagination error.

 error in fetchAllCommentsAPI: {"data":{"listComments":null},"errors":[{"path":["listComments"],"data":null,"errorType":"IllegalArgument","errorInfo":null,"locations":[{"line":2,"column":3,"sourceName":null}],"message":"Invalid pagination token given."}]}

I thought it might be because we need to add a filter for the specific Post we are fetching for but that gave the same error.

Adding a filter to my nextToken graphql call causes an error:

const result = await API.graphql(graphqlOperation(listComments, { filter: { commentPostId: { eq: postId } }, nextToken })); // where commentPostId is the id of the Post.

I dont understand why I am getting that error, I would think the nextToken would take you to that filtered page.

Questions

  1. How can I use nextToken when fetching comments while filtering for a specific post?

  2. Is there a better way to get all comment data efficiently / is extracting is from Post objects bad practice?