Dynamic meta tags in react

The content of meta tags is updating but in the meta preview apps it is not showing the data.

I have made the website for the posts which includes title, description, and a image. my Aim is to create same metatags according to posts so I’m using react and API’s to get the posts and in react I’m rendering the posts into my design also updating the meta tags using helmet lib, but preview apps like WhatsApp, messenger, etc. not showing my content.

I found that ready loads pages client side that’s why they dynamic data cannot be ready by SEO bots.

if anyone have any solution please share with me.
I don’t want to use any third party thing like installing nextJs, Express js, or tools like prerender.io All above required efforts and extra costs. tell me something that i can do with my apache or bots.

Пытаюсь вставить карточки товара в каталог через svelte [closed]

Пишу проект на svelte/sveltekit с помощью flowbite. Основная страница каталога должна брать отдельную страничку с карточкой, и в консоли вывести массив, но вместо этого лишь появляется значение undefind, и на странице каталога пусто. Не пойму в чем дело.

файл +page.svelte в папке /products:

<script>
    import { onMount } from "svelte";
    import ProductCard from "../../components/product/ProductCard.svelte";

    let products = [{}];
    let error = null;

    onMount(async () => {
        try {
            const res = await fetch('http://localhost:3000/product/all');
            
            if (!res.ok) {
                throw new Error(`Error: ${res.status}`);
            }
            
            const data = await res.json();
            products = data.data;

            console.log(products);
        } catch (err) {
            error = err.message;
            console.error('Failed to fetch products:', error);
        }
    });
</script>

<section class="h-[100vh] bg-gray-50 py-8 antialiased dark:bg-gray-900 md:py-12">


      <!--Карточки-->
      <div class="mb-4 grid gap-4 sm:grid-cols-2 md:mb-8 lg:grid-cols-3 xl:grid-cols-4">

            {#each products as product}
                <ProductCard {product} />
            {/each}

      </div>

</section>

<style>
    
</style>

и файл ProductCard, в котором лежит сама карточка:

<div class="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
    <div class="h-56 w-full">
      <a href="#">
        <img class="mx-auto h-full dark:hidden" src="https://flowbite.s3.amazonaws.com/blocks/e-commerce/imac-front.svg" alt="" />
        <img class="mx-auto hidden h-full dark:block" src="https://flowbite.s3.amazonaws.com/blocks/e-commerce/imac-front-dark.svg" alt="" />
      </a>
    </div>
    <div class="pt-6">
      <div class="mb-4 flex items-center justify-between gap-4">
        <span class="me-2 rounded bg-primary-100 px-2.5 py-0.5 text-xs font-medium text-primary-800 dark:bg-primary-900 dark:text-primary-300"> Up to 35% off </span>

        <div class="flex items-center justify-end gap-1">
          <button type="button" data-tooltip-target="tooltip-quick-look" class="rounded-lg p-2 text-gray-500 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
            <span class="sr-only"> Quick look </span>
            <svg class="h-5 w-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
              <path stroke="currentColor" stroke-width="2" d="M21 12c0 1.2-4.03 6-9 6s-9-4.8-9-6c0-1.2 4.03-6 9-6s9 4.8 9 6Z" />
              <path stroke="currentColor" stroke-width="2" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
            </svg>
          </button>
          <div id="tooltip-quick-look" role="tooltip" class="tooltip invisible absolute z-10 inline-block rounded-lg bg-gray-900 px-3 py-2 text-sm font-medium text-white opacity-0 shadow-sm transition-opacity duration-300 dark:bg-gray-700" data-popper-placement="top">
            Quick look
            <div class="tooltip-arrow" data-popper-arrow=""></div>
          </div>

          <button type="button" data-tooltip-target="tooltip-add-to-favorites" class="rounded-lg p-2 text-gray-500 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
            <span class="sr-only"> Add to Favorites </span>
            <svg class="h-5 w-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6C6.5 1 1 8 5.8 13l6.2 7 6.2-7C23 8 17.5 1 12 6Z" />
            </svg>
          </button>
          <div id="tooltip-add-to-favorites" role="tooltip" class="tooltip invisible absolute z-10 inline-block rounded-lg bg-gray-900 px-3 py-2 text-sm font-medium text-white opacity-0 shadow-sm transition-opacity duration-300 dark:bg-gray-700" data-popper-placement="top">
            Add to favorites
            <div class="tooltip-arrow" data-popper-arrow=""></div>
          </div>
        </div>
      </div>

      <a href="#" class="text-lg font-semibold leading-tight text-gray-900 hover:underline dark:text-white">Apple iMac 27", 1TB HDD, Retina 5K Display, M3 Max</a>

      <div class="mt-2 flex items-center gap-2">
        <div class="flex items-center">
          <svg class="h-4 w-4 text-yellow-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24">
            <path d="M13.8 4.2a2 2 0 0 0-3.6 0L8.4 8.4l-4.6.3a2 2 0 0 0-1.1 3.5l3.5 3-1 4.4c-.5 1.7 1.4 3 2.9 2.1l3.9-2.3 3.9 2.3c1.5 1 3.4-.4 3-2.1l-1-4.4 3.4-3a2 2 0 0 0-1.1-3.5l-4.6-.3-1.8-4.2Z" />
          </svg>

          <svg class="h-4 w-4 text-yellow-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24">
            <path d="M13.8 4.2a2 2 0 0 0-3.6 0L8.4 8.4l-4.6.3a2 2 0 0 0-1.1 3.5l3.5 3-1 4.4c-.5 1.7 1.4 3 2.9 2.1l3.9-2.3 3.9 2.3c1.5 1 3.4-.4 3-2.1l-1-4.4 3.4-3a2 2 0 0 0-1.1-3.5l-4.6-.3-1.8-4.2Z" />
          </svg>

          <svg class="h-4 w-4 text-yellow-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24">
            <path d="M13.8 4.2a2 2 0 0 0-3.6 0L8.4 8.4l-4.6.3a2 2 0 0 0-1.1 3.5l3.5 3-1 4.4c-.5 1.7 1.4 3 2.9 2.1l3.9-2.3 3.9 2.3c1.5 1 3.4-.4 3-2.1l-1-4.4 3.4-3a2 2 0 0 0-1.1-3.5l-4.6-.3-1.8-4.2Z" />
          </svg>

          <svg class="h-4 w-4 text-yellow-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24">
            <path d="M13.8 4.2a2 2 0 0 0-3.6 0L8.4 8.4l-4.6.3a2 2 0 0 0-1.1 3.5l3.5 3-1 4.4c-.5 1.7 1.4 3 2.9 2.1l3.9-2.3 3.9 2.3c1.5 1 3.4-.4 3-2.1l-1-4.4 3.4-3a2 2 0 0 0-1.1-3.5l-4.6-.3-1.8-4.2Z" />
          </svg>

          <svg class="h-4 w-4 text-yellow-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24">
            <path d="M13.8 4.2a2 2 0 0 0-3.6 0L8.4 8.4l-4.6.3a2 2 0 0 0-1.1 3.5l3.5 3-1 4.4c-.5 1.7 1.4 3 2.9 2.1l3.9-2.3 3.9 2.3c1.5 1 3.4-.4 3-2.1l-1-4.4 3.4-3a2 2 0 0 0-1.1-3.5l-4.6-.3-1.8-4.2Z" />
          </svg>
        </div>

        <p class="text-sm font-medium text-gray-900 dark:text-white">5.0</p>
        <p class="text-sm font-medium text-gray-500 dark:text-gray-400">(455)</p>
      </div>

      <ul class="mt-2 flex items-center gap-4">
        <li class="flex items-center gap-2">
          <svg class="h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h6l2 4m-8-4v8m0-8V6a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v9h2m8 0H9m4 0h2m4 0h2v-4m0 0h-5m3.5 5.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Zm-10 0a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Z" />
          </svg>
          <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Fast Delivery</p>
        </li>

        <li class="flex items-center gap-2">
          <svg class="h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M8 7V6c0-.6.4-1 1-1h11c.6 0 1 .4 1 1v7c0 .6-.4 1-1 1h-1M3 18v-7c0-.6.4-1 1-1h11c.6 0 1 .4 1 1v7c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1Zm8-3.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z" />
          </svg>
          <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Best Price</p>
        </li>
      </ul>

      <div class="mt-4 flex items-center justify-between gap-4">
        <p class="text-2xl font-extrabold leading-tight text-gray-900 dark:text-white">$1,699</p>

        <button type="button" class="inline-flex items-center rounded-lg bg-primary-700 px-5 py-2.5 text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4  focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
          <svg class="-ms-2 me-2 h-5 w-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4h1.5L8 16m0 0h8m-8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm.75-3H7.5M11 7H6.312M17 4v6m-3-3h6" />
          </svg>
          Add to cart
        </button>
      </div>
    </div>
</div>

Operators Executing Too Soon in JavaScript Calculator

I am building a calculator using JavaScript without using eval(). The number buttons (calculatorNumbers) work fine, but when I click an operator (calculatorOperators), it immediately tries to execute an operation, leading to incorrect results.

Operators (+, -, *, /) execute immediately when clicked instead of waiting for the second number.
The finalAnswer function is called inside the forEach loop for both numbers and operators, causing unintended looping behavior.
Trying to convert the operator into a number results in NaN.

Clicking a number should update the input screen.
Clicking an operator should store the first number and operator but not execute the calculation immediately.
Pressing = should perform the operation using stored values.

// calculator functions

function calculator() {
  calculatorNumbers.forEach((btns) => {
    btns.addEventListener("click", function (event) {
      const btnsValues = Number(event.currentTarget.textContent);
      inputScreen.value += btnsValues;
      finalAnswer(btnsValues);
    });
  });

  calculatorOperators.forEach((opBtns) => {
    opBtns.addEventListener("click", function (event) {
      const targetOpBtns = event.currentTarget.textContent;
      inputScreen.value += targetOpBtns;
      finalAnswer(targetOpBtns);
    });
  });
  deleteOneNumber.addEventListener("click", function () {
    let inputValueLength = Number(inputScreen.value.length - 1);
    let deleteOneValue = inputScreen.value.slice(0, inputValueLength);
    inputScreen.value = deleteOneValue;
  });
  clearAllNumbers.addEventListener("click", function (event) {
    const target = event.currentTarget;
    target ? (inputScreen.value = "") : null;
  });
}

// function call
calculator();

// total function
function finalAnswer(value) {
  //    console.log(number==="*");
  let convertNumber = Number(value)
  if (value === "*") {
    inputScreen.value = (Number(inputScreen.value)) * convertNumber 
  }
  if (value === "-") {
      
    inputScreen.value = (Number(inputScreen.value)) - convertNumber 
  }
  if (value === "+") {
      
    inputScreen.value = (Number(inputScreen.value)) + convertNumber 
  }
  if (value === "/") {
      
    inputScreen.value = (Number(inputScreen.value)) / convertNumber 
  }
}

What do i do im using cloudflare for my website and a cloudflare worker

Access to XMLHttpRequest at 'https://jmfhosting.com/api/auth/register' from origin 'https://www.jmfhosting.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Request Error:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 15000, withCredentials: true, upload: XMLHttpRequestUpload, …}
onabort
:
ƒ ()
onerror
:
ƒ ()
onload
:
null
onloadend
:
ƒ g()
onloadstart
:
null
onprogress
:
null
onreadystatechange
:
null
ontimeout
:
ƒ ()
readyState
:
4
response
:
“”
responseText
:
“”
responseType
:
“”
responseURL
:
“”
responseXML
:
null
status
:
0
statusText
:
“”
timeout
:
15000
upload
:
XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials
:
true
[[Prototype]]
:
XMLHttpRequest

i just want a fix ive tried everything i could search watch etc

React Native Web custom dropdown issue

I am currently trying to create a custom dropdown tool with expo. I have created a custom dropdown component that includes a: DropdownMenu, SearchableDropdown, and Dropdown. When i was implementing these components, it worked as expected – however, it seems like the menu is displaying components behind other components.

I have tried making putting in the z-index into the css for the scrollview, but it did not work. So i have tried inspecting the elements from my webpage. it turns out that the first children below the root element it has a z-index of 0, when i removed it, the dropdown menu works.

this is the DropDown Menu code:

const DropdownMenu: React.FC<DropdownMenuProps> = ({ data, onClick }) => {

  const handleSelect = (item: DropdownItem) => {
    onClick(item);
  };

  return (
    <View>
      <View >
        <ScrollView>
          {data.map((item) => (
            <TouchableOpacity
              key={item.id.toString()}
              onPress={() => handleSelect(item)}
            >
              <Text>{item.label}</Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>
    </View>
  );
};

and this is my component that triggers the search:

<View style={styles.container}>
        {selectedItem ? (
          <TouchableOpacity
            onPress={() => {
              setDropdownVisible(false);
              setSearchText("");
              onSelect(null);
            }}
          >
         
            <Text>{selectedItem.label}</Text>
          </TouchableOpacity>
        ) : (
          <TextInput
            value={searchText}
            onChangeText={(text) => setSearchText(text)}
            onFocus={() => {
              setDropdownVisible(true);
            }}
            onBlur={() => {
              setTimeout(() => {
                if (!selectedItem) {
                  setDropdownVisible(false);
                }
              }, 200);
            }}
            placeholder="Search..."
          />
        )}
        {dropdownVisible && (
          <DropdownMenu data={itemsToDisplay} onClick={onSelect}/>
        )}
      </View>

Does anyone know how to fix this/if there are any other better ways?

Thank you very much for your help

How to filter array of objects with filter with dynamic properties count?

I have an array of objects with some bool and int properties:

let employees = [
  { isSkilled: false, isLeader: false, departmentHeadType: 0 },
  { isSkilled: true, isLeader: false, departmentHeadType: 1 },
  { isSkilled: true, isLeader: true, departmentHeadType: 2 }
]

And there is a select where user can check options (in any combinations) by which employees will be filtered:

enter image description here

So after selection I have a filter something like that:

//if user selected "Skilled", "Leaders" and "Heads of departments"
var filter1 = { isSkilled: true, isLeader: true, departmentHeadType: 2 };
//if user selected "Skilled", "Newbie" (so I simply omit isSkilled property in filter
//as both variants are ok), "Leaders", "Heads of departments" and "Deputy heads of departments"
var filter2 = { isLeader: true, departmentHeadType: [1, 2] };

For filter1 I can use the following code:

const filtered = employees.filter(object => JSON.stringify(filter1) == JSON.stringify(object));

But JSON.stringify works only if compared objects have the same properties in the same order. And it will not work for filter2 where isSkilled is omitted and departmentHeadType is array. For filter2 the only idea I have is several ifs and specific properties filtering in each case (that approach is ugly and and not scalable as employee properties grow and thus filter options increase).

Is there a better and more generic aproach for this?

Re-renders when clicking Copy Clipboard button

I am using monaco-editor and I created a code preview. In the previewer, I want to copy the contents, but everytime I click my copy button, it always rer-renders. What am I missing? or How should I fix this?

This is my Previewer.tsx code:

'use client';

import { useState, useCallback, memo } from 'react';
import { Clipboard, ClipboardCheck } from 'lucide-react';
import { Spinner } from '~/components/platform/Spinner';
import Editor from '@monaco-editor/react';

interface PreviewerProps {
  code: string;
  language: string;
  themeClass: string;
  theme: string;
}

const Previewer = memo(({ code, language, theme, themeClass }: PreviewerProps) => {
  return (
    <div className="relative h-full w-full">
      <div className={`${themeClass} flex text-white gap-x-5 px-3 pt-3`}>
        <ClipboardCopy code={code} />
      </div>

      <Editor
        className={`pt-4 ${themeClass}`}
        height="70vh"
        language={language}
        value={code}
        theme={theme}
        options={{
          readOnly: true,
          minimap: { enabled: false },
          wordWrap: 'on',
          scrollBeyondLastLine: false,
        }}
        loading={
          <div className={`${themeClass} flex w-full h-full items-center justify-center`}>
            <Spinner />
          </div>
        }
      />
    </div>
  );
});

Previewer.displayName = 'Previewer';

export default Previewer;

const ClipboardCopy = memo(({ code }: { code: string }) => {
  const [copied, setCopied] = useState(false);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  }, [code]);

  return (
    <button
      onClick={handleCopy}
      className="flex items-center h-7 ml-auto gap-1 px-2 py-1 bg-gray-700 hover:bg-gray-600 text-white rounded transition-all"
      title="Copy code to clipboard"
      aria-live="polite"
    >
      {copied ? <ClipboardCheck size={16} /> : <Clipboard size={16} />}
      <span className="text-sm">{copied ? 'Copied!' : 'Copy'}</span>
    </button>
  );
});

ClipboardCopy.displayName = 'ClipboardCopy';

I tried implementing the clipboard functionality without using any package. I want to know how to fix the re-rendering. Is it good that I implemented my own instead of using any package?

Did anyone have the issue “Google Place API is not activate map error”?

I try to use my google API key to load the autocomplete results, but it show the error in the graph.

enter image description here

And the second img is the photo of my code.enter image description here

However, I did use the https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&key=API_KEY to test my key and it returns the result.
enter image description here

How to fetch and combine Pokémon list and details using React hooks?

I’m working on a React app that fetches Pokémon data from the PokeAPI. I have two custom hooks:

usePokemonRef: Fetches a list of Pokémon references (name and URL) to query for Pokemon.

usePokemonDetails: Fetches detailed information for a specific Pokémon by its ID.

The problem is that the way the API works is that instead of returning the data along with the Pokémon it returns a list of objects with the corresponding Pokémon reference to the Pokémon.

For example:
If I query the api: GET: https://pokeapi.co/pokemon/

RESULT: {name: “charmander”, url: “https://pokeapi.co/pokemon/1”}

It doesn’t return the data only the name and links to get the data.

I want to combine these hooks to fetch the list of Pokémon and then retrieve their details in a single hook (usePokemon). However, I’m unsure how to do this efficiently while adhering to React’s hook rules.

useData.ts

import { useEffect, useState } from "react";
import apiClient from "../services/api-client";

const useData = <T>(endpoint: string, dependencies: any[] = []) => {
  const [data, setData] = useState<T | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    setIsLoading(true);
    setError(null);

    apiClient
      .get<T>(endpoint)
      .then((response) => {
        setData(response.data);
      })
      .catch((err) => {
        setError(err);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [...dependencies]);

  return { data, isLoading, error };
};

export default useData;

usePokemonRefs.ts

import useData from "./useData";

interface PokemonRef {
  name: string;
  url: string;
}

export interface FetchPokemonResponse {
  count: number;
  next: string;
  previous: string | null;
  results: PokemonRef[];
}

const usePokemonRefs = () => useData<FetchPokemonResponse>("/pokemon");

export default usePokemonRefs;

usePokemonDetails.ts

import useData from "./useData";

export interface Sprites {
  back_default: string | undefined;
  back_female: string | undefined;
  back_shiny: string | undefined;
  back_shiny_female: string | undefined;
  front_default: string | undefined;
  front_female: string | undefined;
  front_shiny: string | undefined;
  front_shiny_female: string | undefined;
}

export interface Pokemon {
  id: number;
  name: string;
  sprites: Sprites;
  types: {
    type: {
      name:
        | "bug"
        | "dark"
        | "dragon"
        | "electric"
        | "fairy"
        | "fighting"
        | "fire"
        | "flying"
        | "ghost"
        | "grass"
        | "ground"
        | "ice"
        | "normal"
        | "poison"
        | "psychic"
        | "rock"
        | "steel"
        | "water";
      url: string;
    };
  }[];
}

const usePokemonDetails = (id: number | string) =>
  useData<Pokemon>(`/pokemon/${id}`, [id]);

export default usePokemonDetails;

I want to be able to leverage the usePokemonDetails hook on the usePokemonRefs hook. Is there any way to do this? BTW I am still a beginner in React.

This is the api I am using: PokeApi.

Suggest a better way to conditionally render components in React

Since it is very common that we use different states to render components conditionally line f codes we write becomes more increasing complexity of the codebase.

Is there a better way to manage this issue.

Below code snippet depits a lines of codes I need to rewrite where I need to render different tables conditionally on the same page.

import TableContainer from '@mui/material/TableContainer';
import TablePagination from '@mui/material/TablePagination';
import { Tab, Tabs } from '@mui/material';
import { _users } from 'src/_mock';
import { DashboardContent } from 'src/layouts/dashboard';

import { Iconify } from 'src/components/iconify';
import { Scrollbar } from 'src/components/scrollbar';

import { TableNoData } from '../table-no-data';
import { UserTableRow } from '../user-table-row';
import { UserTableHead } from '../user-table-head';
import { TableEmptyRows } from '../table-empty-rows';
import { UserTableToolbar } from '../user-table-toolbar';
import { emptyRows, applyFilter, getComparator } from '../utils';

import type { CustomerProps} from '../user-table-row';



// ----------------------------------------------------------------------

export function CustomerView() {
  const table = useTable();
const [value,setValue] =useState("one")
const handleChange = (event: React.SyntheticEvent, newValue: string) => {
  setValue(newValue);
};

const { data, loading, error } = useSelector((state: RootState) => state.customers);
const dispatch = useDispatch<ThunkDispatch<any, any, any>>();
useEffect(() => {
  dispatch(fetchCustomersThunk());
}, [dispatch]);
console.log(data);
  const [filterName, setFilterName] = useState('');

  const dataFiltered: CustomerProps[] = applyFilter({
    inputData: data,
    comparator: getComparator(table.order, table.orderBy),
    filterName,
  });

  const notFound = !dataFiltered.length && !!filterName;


 

  return (
    <DashboardContent>
      <Box display="flex" alignItems="center" mb={5}>
        <Typography variant="h4" flexGrow={1}>
          Customers
        </Typography>
        <Button
          variant="contained"
          color="inherit"
          startIcon={<Iconify icon="mingcute:add-line" />}
        >
          New user
        </Button>
      </Box>

      <Card>
        <Card sx={{ display: 'flex', justifyContent: 'space-between', borderRadius: '0' }}>
          <Box sx={{ width: '100%' }}>
            <Box sx={{ borderBottom: 0, borderColor: 'divider' }}>
              <Tabs
            
                onChange={handleChange}
                value={value}
                textColor="primary"
                aria-label="basic tabs example"
              >
                <Tab value="one"     sx={{ backgroundColor: 'disabled' }} label="All customers" />
                <Tab value="two" label="Agent customers" />
              </Tabs>
            </Box>
          </Box>
          <UserTableToolbar
            numSelected={table.selected.length}
            filterName={filterName}
            onFilterName={(event: React.ChangeEvent<HTMLInputElement>) => {
              setFilterName(event.target.value);
              table.onResetPage();
            }}
          />
        </Card>

        <Scrollbar>
          <TableContainer sx={{ overflow: 'unset' }}>
            <Table sx={{ minWidth: 800, fontSize: '1px' }}>
              <UserTableHead
                order={table.order}
                orderBy={table.orderBy}
                rowCount={_users.length}
                numSelected={table.selected.length}
                onSort={table.onSort}
                onSelectAllRows={(checked) =>
                  table.onSelectAllRows(
                    checked,
                    _users.map((user) => user.id)
                  )
                }
                headLabel={[
                  { id: 'id', label: 'ID' },
                  { id: 'name', label: 'User Name' },
                  { id: 'email', label: 'Email' },
                
             
                  { id: 'mobile', label: 'Mobile Number' },
                  { id: 'agent?', label: 'Is agent' },
             
                ]}
              />
              <TableBody>
                {dataFiltered
                  .slice(
                    table.page * table.rowsPerPage,
                    table.page * table.rowsPerPage + table.rowsPerPage
                  )
                  .map((row) => (
                    <UserTableRow
                      key={row.cus_id}
                      row={row}
                      selected={table.selected.includes(row.cus_id)}
                      onSelectRow={() => table.onSelectRow(row.cus_id)}
                    />
                  ))}

                <TableEmptyRows
                  height={68}
                  emptyRows={emptyRows(table.page, table.rowsPerPage, _users.length)}
                />

                {notFound && <TableNoData searchQuery={filterName} />}
              </TableBody>
            </Table>
          </TableContainer>
        </Scrollbar>

        <TablePagination
          component="div"
          page={table.page}
          count={_users.length}
          rowsPerPage={table.rowsPerPage}
          onPageChange={table.onChangePage}
          rowsPerPageOptions={[5, 10, 25, 100]}
          onRowsPerPageChange={table.onChangeRowsPerPage}
        />
      </Card>
    </DashboardContent>
  );
}

// ----------------------------------------------------------------------

export function useTable() {
  const [page, setPage] = useState(0);
  const [orderBy, setOrderBy] = useState('name');
  const [rowsPerPage, setRowsPerPage] = useState(5);
  const [selected, setSelected] = useState<string[]>([]);
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');

  const onSort = useCallback(
    (id: string) => {
      const isAsc = orderBy === id && order === 'asc';
      setOrder(isAsc ? 'desc' : 'asc');
      setOrderBy(id);
    },
    [order, orderBy]
  );

  const onSelectAllRows = useCallback((checked: boolean, newSelecteds: string[]) => {
    if (checked) {
      setSelected(newSelecteds);
      return;
    }
    setSelected([]);
  }, []);

  const onSelectRow = useCallback(
    (inputValue: string) => {
      const newSelected = selected.includes(inputValue)
        ? selected.filter((value) => value !== inputValue)
        : [...selected, inputValue];

      setSelected(newSelected);
    },
    [selected]
  );

  const onResetPage = useCallback(() => {
    setPage(0);
  }, []);

  const onChangePage = useCallback((event: unknown, newPage: number) => {
    setPage(newPage);
  }, []);

  const onChangeRowsPerPage = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setRowsPerPage(parseInt(event.target.value, 10));
      onResetPage();
    },
    [onResetPage]
  );

  return {
    page,
    order,
    onSort,
    orderBy,
    selected,
    rowsPerPage,
    onSelectRow,
    onResetPage,
    onChangePage,
    onSelectAllRows,
    onChangeRowsPerPage,
  };
}

When I click on delete icon , I get an error but when I click again the element gets deleted

let add_btn = document.querySelector('.add');
let container = document.querySelector('.container');
let createNote = document.querySelector('.create-note');
let create = document.querySelector('.create-btn');
let close = document.querySelector('.close-btn');
let text = '';
let editNote = document.querySelector('.edit-note');
let textArea = document.querySelector('textarea');
let closeBtn = document.querySelector('.close-btn2');
let editBtn = document.querySelector('.edit-btn');
let textArea2 = document.querySelector('.textarea2');
arr = [];
add_btn.addEventListener('click', () => {
  textArea.value = '';
  createNote.style.display = 'block';
})
close.addEventListener('click', () => {
  createNote.style.display = 'none';
})
create.addEventListener('click', () => {
  let note = document.createElement('div'); 
  note.className = 'note';
  let innerNote = document.createElement('div');
  innerNote.className = 'inner-note';
  text = textArea.value;
  innerNote.textContent = text;
  let edit = document.createElement('i');
  edit.className = 'fa-solid fa-edit';
  let del = document.createElement('i');
  del.className = 'fa-solid fa-trash';
  if (!textArea.value){
    return;
  }
  else {
  note.appendChild(innerNote);
  note.appendChild(edit);
  note.appendChild(del);
  container.appendChild(note); 
  createNote.style.display = 'none';
  note.style.display = 'block';
  edit.addEventListener('click', () => {
    let text = edit.closest('.note');
    let text2 = text.querySelector('.inner-note');
    textArea2.value = text2.textContent;
    editNote.style.display = 'block';
  })

  del.addEventListener('click', () => {
    let noteText = document.querySelectorAll('.inner-note');
    let noteText1 = Array.from(noteText);
    let index = noteText1.indexOf(innerDiv1);
    console.log(arr);
    arr.splice(index,1);
    container.removeChild(note);
    console.log(arr);
  })
  noteText = document.querySelectorAll('.inner-note');
  noteText.forEach((val,index) => {
    arr[index] = val.textContent;
    IndexofNote = index;
  });
  console.log(`noteText has a length of ${noteText.length} `);
  console.log(`Note at index ${IndexofNote} ${arr[IndexofNote]} length of array is ${arr.length} `);
  }
});

editBtn.addEventListener('click', () => {
  innerDiv1.textContent = textArea2.value;
  editNote.style.display = 'none';
  noteText.forEach((val,Index) => {
    arr[Index] = val.textContent;
    console.log(`Note at index ${Index} ${arr[Index]}`);  
  });
  console.log(arr);
})

container.addEventListener('click', (event) => {
  let trgt = event.target;
  if (!trgt.matches('.fa-edit') && (!trgt.matches('.fa-trash'))) return;
  const parent = trgt.closest('.note');
  innerDiv1 = parent.querySelector('.inner-note');
  if (trgt.matches('.fa-edit')) {
    editNote.style.display = 'block';
  }  
  if (trgt.matches('.fa-trash')) {
    
  }
})

closeBtn.addEventListener('click', () => {
  editNote.style.display = 'none';
})




* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

body {
  background-color: #8c53ff;
  height: 94vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.container {
  height: 340px;
  width: 665px;
  background-color: white;
  border-radius: 10px;
  display: flex;
  flex-wrap: wrap;
  overflow-y: auto;
}
.add {
  width: 237px;
  height: 241px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  margin-left: 4%;
  margin-top: 3%;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 64px;
  color: gainsboro;
}
.add:hover {
  background-color: #f1f1f1;
}
.create-note {
  width: 441px;
  height: 316px;
  border: 1px solid #ccc;
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  border-radius: 10px;
  position: absolute;
  top: 22%;
  left: 34%;
  display: none;
}
.heading {
  margin-top: 16px;
  font-size: 32px;
}

textarea {
  border: 2px solid #8c53ff;
  border-radius: 10px;
  width: 300px;
  height: 144px;
  margin-left: 5%;
  margin-top: 12px;
  padding: 10px;
}
.create-btn {
  width: 100px;
  height: 36px;
  margin-top: 18px;
  margin-left: 15px;
  background-color: #8c53ff;
  color: white;
}
.close-btn {
  width: 100px;
  height: 36px;
  background-color: gainsboro;
  color: white;
  margin-left: 10px;
}
.create-btn,.close-btn {
  border: none;
  border-radius: 14px;
  font-size: 14px;
}
.note {
  background-color: #fff385;
  height: 240px;
  width: 240px;
  margin: 25px;
  border-radius: 10px;
  overflow-y: auto;
  display: none;
}
.inner-note {
  height: 190px;
  width: 190px;
  overflow-y: auto;
  margin-left: 32px;
  margin-top: 26px;
  word-break: break-all;
  word-spacing: 2px;
}
.fa-solid.fa-edit {
  margin-left: 94px;
}
.fa-solid.fa-trash {
  margin-left: 30px;
}
.edit-note {
  width: 441px;
  height: 316px;
  border: 1px solid #ccc;
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  border-radius: 10px;
  position: absolute;
  top: 22%;
  left: 34%;
  display: none;
}
.edit-btn {
  width: 100px;
  height: 36px;
  margin-top: 18px;
  margin-left: 15px;
  background-color: #8c53ff;
  color: white;
  border: none;
  border-radius: 14px;
  font-size: 14px;
}
.close-btn2 {
  width: 100px;
  height: 36px;
  background-color: gainsboro;
  color: white;
  margin-left: 10px; 
  border: none;
  border-radius: 14px;
  font-size: 14px;
}
@media only screen and (max-width: 600px) {
  .container {
    width: 375px;
    display: block;
  }
  .add {
    margin-left: 20%;
  }
  .create-note {
    left: 0%;
    width: 374px;
  } 
  .note {
    margin-left: 70px;
    overflow-y: clip;
  }
  .inner-note {
    padding-top: 20px;
  }
  .fa-solid.fa-edit {
    padding-top: 10px;
  }
}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Notes App</title>
  <script defer src="script.js"></script>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body>
  <div class="container">
    <div class="add">
      <i class = 'fa-solid fa-plus'></i>
    </div>
    <div class="create-note">
      <h1 class = 'heading'>New Note</h1>
      <textarea name="" id="" placeholder="Enter your note..."></textarea>
      <button class = 'create-btn'>Create Note</button>
      <button class = 'close-btn'>Close</button>
    </div>
    <div class="edit-note">
      <h1 class = 'heading'>Edit Note</h1>
      <textarea name="" id="" class = 'textarea2'></textarea>
      <button class = 'edit-btn'>Edit Note</button>
      <button class = 'close-btn2'>Close</button>
    </div>
  </div>
</body>
</html>

I want the note to be deleted but the values should be stored in the array in the correct order, if 3 notes are there and I delete the second one, the array will delete 1st note, so is there a way we can get the correct array element deleted. I have used event delegation which was suggested to me by someone on StackOverflow.

Why use classes over a function that just returns an object? [duplicate]

So I can make a function that does everything that I class can do (I think). So why would I ever use a class? (Yes this is just an example but you could also put like functions or anything else you want to into a dictionary/object for you JavaScripter’s out there)

class User:
    def __init__ (self, user_id):
        self.id = user_id

user_1 = User("1")

def makeUser(user_id):
    return {
        id:user_id,
        }

user2 = makeUser("2")

How to properly communicate with ‘localhost 8000’ Mongoose database across files?

Is there an offical setup to startup the Mongoose database and the website database to recive the contents database contents?

-> This is my current file setup
-> The idea is to start my Mongoose database with ‘index.js’ (‘package.json’) and use that information to validate/add data in my ‘popup-form.js’ file.

Webiste Folder
| assets
   | css
   | javaScript
      > popup-form.js
   | images
   | saaa
| config
| server
  | node_modules
    > .env
    > index.js
    > package-lock.js
    > package.json
| index.html

This is the contents inside the ‘index.js’ file

const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");

const app = express();
dotenv.config();

const PORT = process.env.PORT || 7000;
const MONGOURL = process.env.MONGO_URL;
console.log("MONGO_URL:", MONGOURL);

mongoose.connect(MONGOURL).then(() => {
    console.log("Database connected");
    app.listen(PORT, () => {
        console.log('Server is running on ' + PORT);
    })
}).catch((error) => console.log(error));

const updatesSchema = ({
    name: String,
    description: String,
    Date: String
});

const UpdateModel = mongoose.model("updates", updatesSchema);

app.use(express.static('public', {
    setHeaders: (res, path) => {
        if (path.endsWith('.js')) {
            res.setHeader('Content-Type', 'application/javascript');
        }
    }
}));

app.get("/getUpdates", async(req, res) => {
    const updatesData = await UpdateModel.find();
    res.json(updatesData);
});

function addUpdate(Update_name, description, time) {
    const newData = new UpdateModel({
        name: Update_name,
        description: description,
        Date: time
    });

    console.log("Attempting to save:", newData);

    newData.save()
        .then(() => console.log("Data saved successfully!"))
        .catch((err) => console.error("Error saving data:", err));
}

function findUpdates() {
    UpdateModel.find({})
    .then((documents) => {
        const dataArray = documents.map((doc) => doc.toObject());
        return dataArray
    })
    .catch((err) => console.error("Error retrieving data:", err));
}

This is where i am trying to apply changes to the Mongoose database

import('./server/index.js').then((module) => {
        const title = document.getElementById("update_title").value.toLowerCase().trim();
        const description = document.getElementById("update_description").value.trim();
        const time = document.getElementById("current_time").innerHTML.trim();
        module.addUpdate(title, description, time);
        module.findUpdates().then((test) => {
            console.log("Fetched updates:", test);
            document.getElementById("update_title").value = "";
            document.getElementById("update_description").value = "";
        }).catch((err) => console.error("Error fetching updates:", err));
    });
    //addUpdate(document.getElementById("update_title").value.toLowerCase().trim(), document.getElementById("update_description").value.trim(), document.getElementById("current_time").innerHTML.trim());

    document.getElementById("update_title").value = "";
    document.getElementById("update_description").value = "";

The file ‘index.js’ always shows the error

MongooseError: The uri parameter to openUri() must be a string, got “undefined”. Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

  • This error was successfully removed to introduce new data to the database by running ‘package.json’ debug file directly. However, now the error came back regardless of the new mythod of running the file.
  • The full project seems unable to reliably have axis to the mongoose database as well.