Mongoose Plugin to filter soft deleted in array docs and root docs using find() and perform soft delete on array docs and root docs

Implementing a Mongoose Plugin for Soft Delete Array doc and root doc Filtering

I am developing a Mongoose plugin to handle soft deletion and filtering of soft-deleted items using find() in a MongoDB database. The plugin needs to:

  1. Automatically filter out soft-deleted documents and nested array items in find() queries.
  2. Provide a method to perform soft deletion on both top-level documents and nested array items.
  3. Allow the option to include soft-deleted items in queries when needed.

My main challenges are:

  • Ensuring the pre-find hook efficiently filters both top-level and nested soft-deleted items.
  • Implementing a flexible soft delete method that works for various document structures.
  • Handling the option to show soft-deleted items without complicating the query process.

I am particularly interested in:

  1. Handling of nested documents and arrays.

Any guidance or example patterns would be greatly appreciated!

Data :

 {
      "_id": {
        "$oid": "66c883a5e6ddbf5f720ae1b6"
      },
      "name": "Some Name",
      "email": "[email protected]",
      "age": 48,
      "nestedArr": [
        {
          "id": 7032086,
          "value": "apple0",
          "isDeleted": false
        },
        {
          "id": 4086837,
          "value": "apple0",
          "isDeleted": true
        },
        {
          "id": 6683277,
          "value": "apple0",
          "isDeleted": false
        },
        {
          "id": 2870389,
          "value": "apple0",
          "isDeleted": true
        }
      ],
      "isDeleted": true,
    }

Why the Theme Toggle works in production but not in development?

I implemented a theme toggle (light/dark mode) on my Astro.js project, and it works perfectly in production. However, in my local development environment, the toggle isn’t functioning. I’ve cleared the cache and checked for JavaScript errors, but the issue persists.

  • What could cause such behavior differences between production and development environments?

  • Could it be related to build settings, environment variables, or something else?

  • Project: Portfolio-cv

  • Production: camilooviedo.com/

ThemeToggle.js

document.addEventListener("DOMContentLoaded", () => {
  // Get elements for both large and small screen theme toggle buttons
  const themeToggleButton = document.getElementById("theme-toggle-btn");
  const themeToggleButtonSm = document.getElementById("theme-toggle-btn-sm");

  // Get elements for light and dark mode icons for both screen sizes
  const lightModeIcon = document.getElementById("light-icon");
  const darkModeIcon = document.getElementById("dark-icon");

  const lightModeIconSm = document.getElementById("light-icon-sm");
  const darkModeIconSm = document.getElementById("dark-icon-sm");

  const applyTheme = (theme) => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");

      // Update icons for large screens
      lightModeIcon.classList.add("hidden");
      darkModeIcon.classList.remove("hidden");

      // Update icons for small screens
      lightModeIconSm.classList.add("hidden");
      darkModeIconSm.classList.remove("hidden");
    } else {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");

      // Update icons for large screens
      darkModeIcon.classList.add("hidden");
      lightModeIcon.classList.remove("hidden");

      // Update icons for small screens
      darkModeIconSm.classList.add("hidden");
      lightModeIconSm.classList.remove("hidden");
    }
  };

  const storedTheme = localStorage.getItem("theme");
  const systemPrefersDark = window.matchMedia(
    "(prefers-color-scheme: dark)"
  ).matches;
  const themeToApply = storedTheme || (systemPrefersDark ? "dark" : "light");

  // Apply the determined theme on page load
  applyTheme(themeToApply);

  // Add event listeners to toggle buttons to switch themes
  themeToggleButton.addEventListener("click", () => {
    const isCurrentlyDark = document.documentElement.classList.contains("dark");
    const newTheme = isCurrentlyDark ? "light" : "dark";
    applyTheme(newTheme);
  });

  themeToggleButtonSm.addEventListener("click", () => {
    const isCurrentlyDark = document.documentElement.classList.contains("dark");
    const newTheme = isCurrentlyDark ? "light" : "dark";
    applyTheme(newTheme);
  });
});

I expected to work in both environments: development & production

How Can I Make the Active Sidebar Item Match the Current URL in Next.js?

I’m working on a Next.js project and I’m trying to make the active sidebar item match the current URL. I tried using the useRouter hooks in a functional component. Despite my efforts, the active item does not seem to update correctly based on the URL.

"use client";
import React, { useState, useEffect } from "react";
import Link from "next/link";
import "@/app/globals.css";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
import {
  Package,
  SquareArrowUpRight,
  HandCoins,
  Users,
  ScanEye,
  LayoutDashboard,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export default function Sidebar() {
  const [activeItem, setActiveItem] = useState(0);
  const handleItemClick = (index) => setActiveItem(index);
  const allItemClass =
    "flex items-center gap-3 rounded-lg px-3 py-2 transition-all";
  const activeItemClass =
    "bg-primary text-white dark:bg-primary dark:text-black";
  const inactiveItemClass = "text-muted-foreground hover:text-primary";
  const { setTheme } = useTheme();

  // Ensure theme is set on the client side
  useEffect(() => {
    setTheme("system");
  }, [setTheme]);

  return (
    <div className="flex min-h-screen w-1/4">
      <div className="hidden border-r bg-muted/40 md:block">
        <div className="flex h-full max-h-screen flex-col gap-2">
          <div className="flex h-14 items-center border-b px-4 lg:h-[60px] lg:px-6">
            <Link
              href="/dashboard"
              className="flex items-center gap-2 font-semibold"
            >
              <ScanEye className="h-6 w-6" />
              <span className="">Reebews</span>
            </Link>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="outline"
                  size="icon"
                  className="ml-auto w-8 h-8"
                >
                  <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
                  <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
                  <span className="sr-only">Toggle theme</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => setTheme("light")}>
                  Light
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setTheme("dark")}>
                  Dark
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setTheme("system")}>
                  System
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          <div className="flex-1">
            <nav className="grid items-start px-2 text-sm font-medium lg:px-4">
              <Link
                href="/dashboard"
                className={`${allItemClass} ${
                  activeItem === 0 ? activeItemClass : inactiveItemClass
                }`}
                onClick={() => handleItemClick(0)}
              >
                <LayoutDashboard className="h-4 w-4" />
                Dashboard
              </Link>
              <Link
                href="/campaigns"
                className={`${allItemClass} ${
                  activeItem === 1 ? activeItemClass : inactiveItemClass
                }`}
                onClick={() => handleItemClick(1)}
              >
                <SquareArrowUpRight className="h-4 w-4" />
                Campaign Manager
              </Link>
              <Link
                href="/products"
                className={`${allItemClass} ${
                  activeItem === 2 ? activeItemClass : inactiveItemClass
                }`}
                onClick={() => handleItemClick(2)}
              >
                <Package className="h-4 w-4" />
                Products{" "}
              </Link>
              <Link
                href="/rewards-center"
                className={`${allItemClass} ${
                  activeItem === 3 ? activeItemClass : inactiveItemClass
                }`}
                onClick={() => handleItemClick(3)}
              >
                <HandCoins className="h-4 w-4" />
                Rewards Center
              </Link>
              <Link
                href="/customer-list"
                className={`${allItemClass} ${
                  activeItem === 4 ? activeItemClass : inactiveItemClass
                }`}
                onClick={() => handleItemClick(4)}
              >
                <Users className="h-4 w-4" />
                Customer List
              </Link>
            </nav>
          </div>
          <div className="mt-auto p-4">
            <Card x-chunk="dashboard-02-chunk-0">
              <CardHeader className="p-2 pt-0 md:p-4">
                <CardTitle>Upgrade to Pro</CardTitle>
                <CardDescription>
                  Unlock all features and get unlimited access to our support
                  team.
                </CardDescription>
              </CardHeader>
              <CardContent className="p-2 pt-0 md:p-4 md:pt-0">
                <Button size="sm" className="w-full">
                  Upgrade
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

How can I make the active sidebar item match the current URL so that the active item updates correctly based on the URL?

Is it allowed to assign a child component to a const (inside the parent component) before returning it from a parent component?

I’d like to know whether this code: const linkButtonMovableElement, so storing another component’s invocation (not sure whether this is the correct term) in a parent component is acceptable / OK. Or maybe it’s not? Will it break something? Is it a bad practice to do it like that?

My code:

export function LinkButton(props: LinkButtonProps & HasChildren) {
  const { $type, children } = props;
  const [isActive, setIsActive] = useState(false);
  function onHoverIn() {
    setIsActive(true);
  }
  function onHoverOut() {
    setIsActive(false);
  }

  const linkButtonMovableElement = (
    <AnimatePresence>
      {isActive && (
        <motion.span
          className="link-button__movable-element"
          animate={{ width: "100%" }}
          exit={{ width: 0 }}
        />
      )}
    </AnimatePresence>
  );

  if ($type === "button") {
    const { onClick: onClickCallback } = props;
    return (
      <StyledButton
        animate={{
          color: isActive ? "var(--color-white)" : "var(--color-black)",
        }}
        onClick={onClickCallback}
        onMouseOver={onHoverIn}
        onMouseLeave={onHoverOut}
      >
        {children}
        {linkButtonMovableElement}
      </StyledButton>
    );
  }
  if ($type === "navlink" || $type === "link") {
    const {
      to,
      onHoverIn: onHoverInCallback,
      onHoverOut: onHoverOutCallback,
    } = props;
    function onHoverInLink() {
      onHoverIn();
      onHoverInCallback?.();
    }
    function onHoverOutLink() {
      onHoverOut();
      onHoverOutCallback?.();
    }
    return (
      <StyledLink
        animate={{
          color: isActive ? "var(--color-dark-grey)" : "var(--color-black)",
        }}
        onMouseOver={onHoverInLink}
        onMouseLeave={onHoverOutLink}
        as={$type === "navlink" ? NavLink : Link}
        style={{
          padding: $type === "navlink" ? "1.4rem" : "",
          textTransform: $type === "navlink" ? "uppercase" : "none",
        }}
        to={to}
      >
        {children}
        {linkButtonMovableElement}
      </StyledLink>
    );
  }
}

How to run a Nest.js scheduled function in a different timezone?

I’m struggling getting timezones and task scheduling work properly on a Nest.js 9 project. For reference, this is the docs for the library: https://docs.nestjs.com/v9/techniques/task-scheduling

This is a brief explanation on the current situation… Let’s imagine I want to execute a function at 10:00 A.M Buenos Aires time (GMT-3). This timezone should be equivalent to 09:00 A.M New York time (GMT-4).

So, if I’m in Buenos Aires, and I write this code:

    const cronExecutionDate = new Date('2024-09-23T08:00:00');
    const job = new CronJob(cronExecutionDate, () => console.log('Logging via cron job!'), null, true, 'America/New_York');

I should see the console log statement executing at 09:00 A.M my time. However, I’m not actually seeing that, but the console.log executes at 08:00 A.M my time, even though I’m one hour ahead.

On the other hand, let’s say that my time is 08:00 A.M. If I set the scheduled date as 07:30 A.M in America/New_York timezone, Nest.js throws an error, saying that the date I specified is in the past, even though that’s not true for my timezone, since the equivalent in America/Buenos_Aires is 08:30 A.M.

Could you guys help me figure this out?

Adding different rules each time in jQuery Builder

Every time a new rule is added, it is always the same. Is it possible that every time a new rule is created it is different? Fiddle

If not, how can I modify a newly created rule to be the one I want? In the afterAddRule event I get undefined when I try to access the value and filters.

.on("afterAddRule.queryBuilder", function (event, rule) {
    console.log(rule.value)
 })

Cross-site scripting (XSS) vulnerability fix in Angular/Javascript

I have been trying to fix this Cross-site Scripting XSS vunlerability reported during snyk scanning.

const form = document.createElement('form');
form.method = 'POST';
form.action = data.action;
const element = document.createElement('input');
element.setAttribute('value', 'value_1');
element.setAttribute('name', 'name_1');
element.setAttribute('id', 'id_1');
form.appendChild(element);
document.body.appendChild(form);
//At this .appendChild Synk scan is detecting a XSS vulnerability
form.submit();

It is being reported at line, at appendChild method: –

document.body.appendChild(form);

enter image description here

Please, help me fix this vulnerability.

Are there tools for inspecting references to a javascript object?

I have created several objects in javascript program and decided to check – whether the JS garbage collector disposed them. I have used WeakRef() to check it, but deref() returned object reference (not undefined).

The question is – are there tools (Firefox 112), that allow me to get info – how many references to the object are retained, and which objects refer to my target object (to make it easier to find – why the object is not freed) ?

How do I get the Keycloak users that are part of the same client?

I am making a platform using Nodejs in which you authenticate with Keycloak. Right now I am working with an update for the user management of that platform.

In order to do this, I need to get all the users that are part of the same Keycloak client. Then I will do some manipulations on my own which I have already solved.

However, from what I have searched I do not think that Keycloak has a feature in which i can get the user emails that are part of the same client. Is there a workaround after this?

select option in each row of table. after gave inputs to that table, how can i get each row’s select tag value and its text in a for loop [duplicate]

select option in each row of table. after gave inputs to that table, how can i get each row’s select tag value and its text in a for loop

its my size table script

function sizeadd()
{
    var mytable =  document.getElementById("sizenames");
    var rows = mytable.rows.length;

    var r1 = mytable.insertRow(rows);
    r1.id = mytable.rows.length-1;
    var c1 = r1.insertCell(0);
    var c2 = r1.insertCell(1);

    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    var txtSizePop = document.createElement("select");
    txtSizePop.style.width = '100px';
    txtSizePop.className = 'txtSizeSelection';
    txtSizePop.id="txtSizePop"+r1.id;
    
    c1.appendChild(checkbox);
            
    <?php
        require('connection.php');
        $sqlSize = "select * from msize order by name asc";
        $rsSize = mysqli_query($con, $sqlSize); 
    ?>

    var sizeoption = document.createElement("option");
    sizeoption.value = "-1";
    sizeoption.text = "Select Size";
    txtSizePop.appendChild(sizeoption);
    c2.appendChild(txtSizePop);
    <?php while ($row = mysqli_fetch_array($rsSize)) { ?>
        var sizeoption = document.createElement("option");
        sizeoption.value = "<?php echo $row["code"]; ?>";
        sizeoption.text = "<?php echo $row["name"]; ?>";
        sizeoption.label = "<?php echo $row["name"]; ?>";
        txtSizePop.appendChild(sizeoption);
        c2.appendChild(txtSizePop);
    <?php } ?>
}

i am trying this table’s select tag value and text in other one script

function SizeUpdate()
{
var mystyletable4U = document.getElementById("sizenames");
var rows = mystyletable4U.rows.length;

for(var i = 1; i <= rows-1 ; i++)
    {  
    alert(i);
    var Rowid4Siz = mystyletable4U.rows[i].cells[1].children[0].value;
    var Label4Siz = mystyletable4U.rows[i].cells[1].children[0].text;
    }  

here i got select tag value, but unable to get text

Handling output from koffi library

I am using koffi (koffi.dev) to read my dll function

My dll: mylib.dll

Above is my js code:

const koffi = require('koffi');

const lib = koffi.load('mylib.dll');
// console.log(lib) // this load ok
const setup = lib.func('setup', 'int', ['const wchar_t *', 'wchar_t **']);
// console.log(setup) // this function load ok

const inputJson = {
    "config": {
        "pass": "123"
    }
}
const jsonString = JSON.stringify(inputJson);

// Function to convert a string to a buffer with wide characters (UTF-16)
function stringToWideCharBuffer(str) {
    const buffer = Buffer.alloc((str.length + 1) * 2); // +1 for null-terminator, *2 for 2 bytes per wchar
    buffer.write(str, 0, 'utf16le');
    return buffer;
}

const jsonConfig = stringToWideCharBuffer(jsonString);

// Allocate memory for the output buffer
const jsonOutBuffer = koffi.alloc('wchar_t*', 1024+1); // I am trying to another way but do not able to get the output

// Step 4: Call the function
const result = setup(jsonConfig, jsonOutBuffer);
console.log(result) // result is 0 meaning it successfully, but output come from jsonOutBuffer

// Step 5: Process the result
// Check the result and process the output
if (result === 0) {
    // Convert the wide character buffer to a UTF-8 string

    console.log('Output JSON:', koffi.decode(jsonOutBuffer, 'wchar_t', -1)); // thinking to get the value at here
} else {
    console.error('setup failed with code:', result);
}

I am thinking that my output value is incorrect, could you help me to point the output value as well?

load event doesn’t fire in iframe when code is broken up with setTimeout

I have a number of functions in a task list that need to initialise at certain points i.e. immediate (in an IIFE), domContentLoaded, and load.

This creates lots of long running tasks on the main thread, which block the UI.

I’m trying to break those up, so when each “task” is executed, I wrap it in a setTimeout(task, 0).

This works perfectly, each function runs in its own task and UI is considerably more responsive when loading.

However, if I load a page in an iframe, any of those (immediate) functions which need a window.load event i.e. to hide a loader, don’t fire.

This is how the queue is processed:

    function _initialisers(obj) {
        for (const [key, func] of Object.entries(obj)) {
            setTimeout(func, 0);
        }
    };

    _initialisers(initialisersImmediate);

    window.addEventListener("DOMContentLoaded", function domContentLoaded() {
        _initialisers(initialisersDOMContentLoaded);
    });

    window.addEventListener("load", function pageLoad() {
        _initialisers(initialisersPageLoad);
    });

This is an example of how one of the items is added to the task queue:

 _framework.init(NAME, INIT.IMMEDIATE, function () {
     let loader = document.getElementById(ID_LOADER);

     if (loader.classList.contains(CSS_SHOW_BY_DEFAULT)) {
         window.addEventListener("load", hide); // Fires in main window but not iframe
     }
 });

The INIT.IMMEDIATE specifies how it should execute. Only immediate functions are allowed to define events such as load.

If I remove the timeout, everything works fine.

I wondered if someone could shed some light on why this might be happening?

Flatlist contains empty space

I tried to display my posts using Flatlist (gensture-handler) + setup infinite scroll to load new posts. when i scrolling the flatlist, i have an empty space (idk why). as you can see on screenshot, scrollview thumb in the center of scrollview, but there empty space

screenshot

NEW POST COMPONENT

import { t } from 'i18next';
import { useEffect, useState, useCallback } from 'react';
import { View, FlatList, Text } from 'react-native';
import { api } from '../../../../services/Api';
import { IPost } from '../../../../types';
import Button from '../../../common/Button';
import CardSkeleton from '../../../common/CardSkeleton';
import { ScreenContainer } from '../../../containers/ScreenContainer';
import { PostCard } from '../../Post/PostCard/PostCard';
import HomeSection from '../molecules/HomeSection/HomeSection';
import { twMerge } from 'tailwind-merge';

const MoreNewPosts = () => {
  const [search, { data, isLoading, isSuccess }] =
    api.useSearchByQueryMutation();
  const [currentPage, setCurrentPage] = useState(1);
  const [allPosts, setAllPosts] = useState<IPost[]>([]);

  useEffect(() => {
    loadPosts(1);
  }, []);

  const loadPosts = (page: number) => {
    search({
      page,
      sort_by: 'newest',
    }).then((response) => {
      if (response && 'data' in response) {
        setAllPosts((prevPosts) => {
          const newPosts = response.data.posts.filter(
            (post) => !prevPosts.some((prevPost) => prevPost.id === post.id),
          );
          return [...prevPosts, ...newPosts];
        });
      }
    });
  };

  const handleLoadMore = () => {
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    loadPosts(nextPage);
  };

  const renderItem = ({ item, index }: { item: IPost; index: number }) => (
    <View key={item.id} className={twMerge(index % 2 === 0 ? 'mr-2' : 'ml-2')}>
      <PostCard post={item} isLoading={isLoading} />
    </View>
  );

  const renderFooter = () => {
    if (isLoading) {
      return Array.from({ length: 10 }).map((_, index) => (
        <CardSkeleton key={index} isLoading={isLoading} />
      ));
    }
    return null;
  };

  return (
    <ScreenContainer
      edges={['left', 'right', 'bottom']}
      className="flex-1 bg-white"
    >
      <HomeSection
        label={t('translation:dashboard.fresh_posts.message')}
        elementsAlign="end"
      >
        {allPosts.length ? (
          <FlatList
            data={allPosts}
            numColumns={2}
            renderItem={renderItem}
            keyExtractor={(item) => item.id.toString()}
            onEndReached={handleLoadMore}
            onEndReachedThreshold={0.5}
            ListFooterComponent={renderFooter}
            removeClippedSubviews
          />
        ) : null}
      </HomeSection>
    </ScreenContainer>
  );
};

export default MoreNewPosts;

POST CARD COMPONENT

import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { t } from 'i18next';
import { memo, useState } from 'react';
import { Pressable, Text, View, ViewStyle } from 'react-native';
import { Image } from 'react-native';
import Carousel from 'react-native-reanimated-carousel';
import { twMerge } from 'tailwind-merge';

import { useAppSelector } from '../../../../hooks/useActions';
import { getShortProductName } from '../../../../lib/text';
import { IPost } from '../../../../types';
import {
  CompositeRootStackNavigationProp,
  RootStackParamList,
} from '../../../../types/types';
import { getPostPrice } from '../../../../utils/get';
import LikeComponent from '../LikeComponent/LikeComponent';
import DefaultAvatar from '../../../common/DefaultAvatar';
import Chip from '../../../common/Chip';

export const PostCard = memo(
  ({
    post,
    className,
    style,
    isLoading,
    shouldResize = true,
    isFilter,
  }: {
    post: IPost;
    className?: string;
    style?: ViewStyle;
    isLoading?: boolean;
    shouldResize?: boolean;
    isFilter?: boolean;
  }) => {
    const navigation = useNavigation<CompositeRootStackNavigationProp>();
    const { activeCurrency, isAuthorized } = useAppSelector(
      (state) => state.authReducer,
    );

    return (
      <Pressable
        onPress={() => {
          navigation.push('Tabs', {
            screen: 'HomeStack',
            params: {
              screen: 'Post',
              params: { id: post.id },
            },
          });
        }}
        className={twMerge(
          'relative rounded-[10px] rounded-t-[20px] bg-[#f5f5f5] min-w-[170px] max-w-[50%] flex-1',
          className,
        )}
        style={{
          height: 250,
          ...style,
        }}
      >
        <View
          style={{ backgroundColor: post.used ? '#F8D7A9' : '#99D6A6' }}
          className="absolute left-2 top-2 justify-center items-center rounded-[20px] px-2 py-[5px] z-50"
        >
          <Text
            style={{
              color: post.used ? '#D96804' : '#017B1C',
            }}
            className="text-[12px] font-semibold"
          >
            {post.used
              ? t('translation:product_card.used.message')
              : t('translation:product_card.new.message')}
          </Text>
        </View>

        {isAuthorized && <LikeComponent post={post} />}

        <Image
          height={150}
          className="self-center w-full rounded-[20px] rounded-b-[0px] border-2 border-[#f5f5f5]"
          source={
            post.images_variants.length
              ? { uri: post.images_variants[0].original }
              : require('../../../../../assets/default_image.png')
          }
        />

        <View className="py-[3px] w-full px-[7px]">
          <View className="flex-row justify-between items-center">
            <Text className=" text-[18px] font-medium">
              {post.price === null
                ? t('translation:product_card.discussed.message')
                : post.price == 0.0
                  ? t('translation:product_card.free.message')
                  : getPostPrice(post, activeCurrency)}
            </Text>

            <Text className="text-[12px] font-normal">
              {post.user_location?.name}
            </Text>
          </View>

          <Text
            numberOfLines={2}
            ellipsizeMode="tail"
            className="text-[14px] mb-2 min-h-[40px] max-h-[40px] font-normal"
          >
            {post.title}
          </Text>

          <View className="flex-row py-1 items-center">
            {post.user.avatar ? (
              <Image
                className="rounded-full w-4 h-4"
                source={{ uri: post.user.avatar }}
              />
            ) : (
              <DefaultAvatar size={16} username={post.user.username} />
            )}

            <Text
              className="text-[12px] font-normal ml-1"
              numberOfLines={1}
              ellipsizeMode="tail"
            >
              {post.user.username}
            </Text>
          </View>
        </View>
      </Pressable>
    );
  },
  (prevProps, nextProps) => {
    return prevProps.post === nextProps.post;
  },
);

I tried different keys, optimize the post card. before that I just had a “load more” button and everything worked fine (using scrollview). however when I tried infinite scroll, everything broke

issue with nodejs SyntaxError: Unexpected token < in JSON at position 0 [duplicate]

I got 2 files, app.js and bot.js. App.js is supposed to receive data off stripe which successfully does so and send that data to bot.js which does receive it.

Issue I’m having is SyntaxError: Unexpected token < in JSON at position 0 (can be seen on second image)

Both images are from bot.js
This is what bot.js returns

part 2 of what bot.js returns

Here’s parts of code which sends and receives that data:

app.js

app.post('/cantshowthispart', express.json({
    type: 'application/json'
}), async (request, response) => {
    const event = request.body;

    try {
        switch (event.type) {
            case 'checkout.session.completed':
                console.log('Checkout session was successful!');
                const sessionPaymentData = event.data.object;
                if (sessionPaymentData.payment_method_types.includes('paypal')) {
                    console.log('Payment method: PayPal');
                }
                console.log(sessionPaymentData);
                
                await axios.post('http://localhost:3001/checkoutSessionCompleted', sessionPaymentData, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                break;

            default:
                console.log(`Unhandled event type ${event.type}`);
        }

        response.json({ received: true });
    } catch (error) {
        console.error('Error handling the event', error);
        response.status(500).json({ error: 'Internal Server Error' });
    }
});

bot.js

app.post('/checkoutSessionCompleted', async (req, res) => {
  console.log('RECEIVED SOME DATA')

  // Handle the received data
  const reqData = req.body
  console.log(reqData)
  if (!reqData) {
    console.log('Request body is undefined!')
    return
  }


  console.log(reqData)
})

Everything else works, this part is only thing that’s bugging me.
Any help is appreciated!

Email -Verification page , where a user will be directed to verify his registration with the code sent to his email. using html,css, & javascript

I have on the nav-bar the logo(cinityspace) at immediate left of the nav, then home, workspace, location, about us, signup/login. I have built the signup page, login page, then the home page. now i want to built the Email verification, where immediately after the user’s signup, it would direct the user to the email verification, where the user will get a code via his email to verify his registration process. at the email verification, i will also have the same content & information i have at the home page, from the header, down to the footer. and a full verification js that will generate the code and ensure it matches the users details

I’m expecting a well detailed email-verification page