Compare two array of objects and push or pop objects from first array based on second array

consider below 2 array of objects, say arr1 and arr2.
based on id, if any new item exist in arr2 copy item to arr1 and remove item from arr1 if that item not present in arr2.

const arr1 = [
      {name: "name1", id: 1},
      {name: "name2", id: 2},
      {name: "name3", id: 3}
    ];

    const arr2 = [
      {name: "name1", id: 1},
      {name: "name2", id: 4},
      {name: "name3", id: 3}
    ];

required output

output = `[ 
{name: "name1", id: 1},
{name: "name3", id: 3},
{name: "name2", id: 4} 
]`

express.js not sending response

In the following code, I’m forcing an error. GOT error is printed on console so the program is going in catch block, but express never sends a response with statusCode 500.

app.get("/", async (req, res) => {
  try {
    res.setHeader("Cache-control", `public, max-age=${maxAge}`);

    await pipeline(got.stream(someUrl), res);
  } catch (error) {
    if (error instanceof RequestError) {
      console.error("GOT Error", error.message);
    } else {
      console.error("Some other Error", (error as Error).message);
    }

    res.sendStatus(500);
  }
});

Here is a screenshot from client

enter image description here

Expected result: express should send response with statusCode 500.

Repeated requests via AJAX get slower and slower

Once I kept repeatedly inputting a character in the search box, it is getting slower and slower until it hangs. I wanted to optimize it and make it smoother.

Can you guys help me or give me any advice for what I should do? I am getting the data correctly it just once I tried to search repeatedly without refreshing the page it is getting laggy.

This is my model:

public class TrieNode
    {
        public List<string> Titles { get; set; }
        public Dictionary<char, TrieNode> Children { get; set; }
        public bool IsEndOfWord { get; set; }
        public int Popularity { get; set; }

        public TrieNode()
        {
            Titles = new List<string>();
            Children = new Dictionary<char, TrieNode>();
        }
    }

This is my service:

public void Insert(string title)
        {
            var node = _trie;
            foreach (var ch in title)
            {
                if (!node.Children.ContainsKey(ch))
                {
                    node.Children[ch] = new TrieNode();
                }
                node = node.Children[ch];
            }

            if (node.Titles != null)
            {
                node.Titles.Add(title);
            }
            else
            {
                node.IsEndOfWord = true;
            }

            if (node.Titles != null && node.Titles.Count >= Threshold)
            {
                ConvertListToTrie(node);
            }
        }

        private void ConvertListToTrie(TrieNode node)
        {
            foreach (var title in node.Titles)
            {
                Insert(title);
            }
            node.Titles = null;
        }

        /* Search to get exact titles and with levenshtein then sort by latest visit first then popularity and titles asc then lastly with levenshtein*/
        public List<(string title, int popularity)> Search(string prefix)
        {
            var node = _trie;
            foreach (var ch in prefix)
            {
                if (!node.Children.ContainsKey(ch))
                {
                    return new List<(string, int)>();
                }
                node = node.Children[ch];
            }
            return GettitlesFromNode(prefix, node);
        }

        private List<(string title, int popularity)> GettitlesFromNode(string prefix, TrieNode node)
        {
            var titles = new List<(string title, int popularity)>();
            if (node.IsEndOfWord)
            {
                titles.Add((prefix, node.Popularity));
            }
            foreach (var child in node.Children.OrderByDescending(c => c.Value.Popularity))
            {
                titles.AddRange(GettitlesFromNode(prefix + child.Key, child.Value));
            }
            return titles;
        }

        public List<(string title, int popularity)> GetSuggestionsWithLevenshtein(string query)
        {
            var exactMatches = Search(query);
            var additionalSuggestions = new List<(string title, int popularity)>();

            if (exactMatches.Count < 10)
            {
                additionalSuggestions = FindSimilarTitles(query)
                    .Select(w => (title: w, popularity: GetPopularityFromTrie(w)))
                    .Where(w => !exactMatches.Any(s => s.title == w.title))
                    .Take(10 - exactMatches.Count)
                    .ToList();
            }

            return exactMatches.Select(s => (s.title, s.popularity))
                    .Concat(additionalSuggestions)
                    .OrderByDescending(s => s.popularity)
                    .ThenBy(s => s.title)
                    .ThenBy(s => Levenshtein(query, s.title))
                    .ToList();
        }

        /* Get Popularity and Last Visit of each title */
        private int GetPopularityFromTrie(string title)
        {
            var node = _trie;
            foreach (var ch in title)
            {
                if (!node.Children.ContainsKey(ch))
                {
                    return 0;
                }
                node = node.Children[ch];
            }
            return node.IsEndOfWord ? node.Popularity : 0;
        }

        /* Find Titles with levenshtein distance */
        private List<string> FindSimilarTitles(string input)
        {
            var results = new List<string>();
            foreach (var title in GetAllTitles(_trie, ""))
            {
                if (Levenshtein(input, title) <= 2)
                {
                    results.Add(title);
                }
            }
            return results;
        }

        public List<string> GetAllTitles(TrieNode node, string prefix)
        {
            var titles = new List<string>();
            if (node.IsEndOfWord)
            {
                titles.Add(prefix);
            }
            foreach (var child in node.Children)
            {
                titles.AddRange(GetAllTitles(child.Value, prefix + child.Key));
            }
            return titles;
        }

        private int Levenshtein(string input, string target)
        {
            if (input == target)
            {
                return 0;
            }

            if (input.Length == 0)
            {
                return target.Length;
            }

            if (target.Length == 0)
            {
                return input.Length;
            }

            int[,] distance = new int[input.Length + 1, target.Length + 1];

            for (int i = 0; i <= input.Length; i++)
            {
                distance[i, 0] = i;
            }

            for (int j = 0; j <= target.Length; j++)
            {
                distance[0, j] = j;
            }

            for (int i = 1; i <= input.Length; i++)
            {
                for (int j = 1; j <= target.Length; j++)
                {
                    int cost = input[i - 1] == target[j - 1] ? 0 : 1;

                    distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
                }
            }
            return distance[input.Length, target.Length];
        }

This is my controller:

static TrieController()
        {
            var titles = System.IO.File.ReadAllLines("./assets/titles.txt");

            foreach (var title in titles)
            {
                if (Regex.IsMatch(title, "^[a-z\s]+$", RegexOptions.IgnoreCase))
                {
                    _trieService.Insert(title.ToLower());
                }
            }
        }

        [HttpGet]
        public IActionResult GetSuggestions(string title)
        {
            var suggestions = _trieService.GetSuggestionsWithLevenshtein(title)
                               .Select(s => new { title = s.title, popularity = s.popularity });
            return Ok(suggestions.Take(10));
        }

This is the app.js:

let visitedTitles = JSON.parse(localStorage.getItem('visitedTitles')) || [];

/* Suggestions */
function getSuggestions()
 {
    const query = $('#search-box').val();
    if (query.length === 0) {
      $('#suggestions').empty();
      return;
    }
  
    $.ajax({
      //url: `http://ec2-3-25-135-98.ap-southeast-2.compute.amazonaws.com/trie/`,
      url: `https://localhost:7223/trie/`,
      data: { title: query },
      success: function (data) {
        displaySuggestions(data);
      }
    });
  
  $('#clear-button').click(function() 
  {
    $('#search-box').val('');
    $('#suggestions').empty();
    $(this).hide(); 
  });
  
  $('#search-box').on('input', function() 
  {
    const query = $(this).val();
    if (query.length > 0) {
      $('#clear-button').show();
    } else {
      $('#clear-button').hide(); 
    }
    getSuggestions();
  });
}

function displaySuggestions(suggestions) 
{
  const suggestionList = $('#suggestions');
  suggestionList.empty();
  
  const sortData = suggestions.map(title => {
    const visitedItem = visitedTitles.find(item => item.title === title.title);
    return {
      ...title,
      visitDate: visitedItem ? visitedItem.date : null 
    };
  });

  sortData.sort((a, b) => {
    const dateA = new Date(a.visitDate);
    const dateB = new Date(b.visitDate);

    if (isNaN(dateA.getTime()) && isNaN(dateB.getTime())) {
      return 0;
    } else if (isNaN(dateA.getTime())) {
      return 1;
    } else if (isNaN(dateB.getTime())) {
      return -1;
    } else {
      return dateB.getTime() - dateA.getTime();
    }
  });
  sortData.forEach(suggestion => {
    const isVisited = visitedTitles.some(item => item.title === suggestion.title);

    if (isVisited) 
    {
      const visitedItem = visitedTitles.find(item => item.title === suggestion.title);
      lastVisited = calculateTimeDifference(visitedItem.date);
    }
      
    const suggestionItems = $(
        '<li class="list-group-item border-bottom d-flex btn btn-outline-success" width="200px;">' +
            '<span class="suggestion-title "><i class="fa-solid fa-magnifying-glass fa-xs me-3" style="color: #c4c4c4;"></i>' + suggestion.title + '</span>' + 
            '<span class="text-body-tertiary ms-2" style="scale: 0.7;"><i class="fa-duotone fa-solid fa-eye fa-sm me-1"></i>' + suggestion.popularity + '</span>' + 
        '</li>'
    );

    if(isVisited) {
        suggestionItems.addClass('visited');
    }

  suggestionList.append(suggestionItems);
  });
  

  $('#suggestions').on('click', 'li', function () 
  {
      const title = $(this).find('.suggestion-title').text();
      const currentDate = new Date();
      const gmtPlus8Date = new Date(currentDate.getTime() + 8 * 60 * 60 * 1000);
      const formattedDate = gmtPlus8Date.toISOString().slice(0, 19);

      const visitedItem = {
        title: title,
        date: formattedDate
      };
      visitedTitles.push(visitedItem);
      getByName(title);
      visitedTitles.push(title);
      localStorage.setItem('visitedTitles', JSON.stringify(visitedTitles));
      $('#search-box').val('');
      $('#suggestions').empty();
  });
}

$(document).ready(function() 
{
const debouncedGetSuggestions = debounce(getSuggestions, 300);
  $('#search-box').on('input', debouncedGetSuggestions, function() {
    currentSearchPage = 1;
    getSuggestions();
  });
})

React Native modal TextInput doesn’t work

The keyboard does not appear and I cannot add quantity.

View:

import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  ActivityIndicator,
  Modal,
  StyleSheet,
  Alert
} from "react-native";
import { globalStyles } from "../globalStyles.js";
import { styles } from "./styles.js"; // Importamos los estilos desde styles.js
import * as RootNavigation from "../../utils/navigator/RootNavigation.js";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { PedidosComercialLogic } from "./PedidosComercialLogic";
import { Button } from "@rneui/themed";
import { FlashList } from "@shopify/flash-list";
import { SearchInput } from "../otros/SearchInput";
import { useGlobalContext } from "../../utils/context/GlobalContextProvider.js";
import { useInternetContext } from "../../utils/context/InternetContextProvider.js";
import { PdaUser } from "../../class/PdaUser.class";
import QuantitySelector from "../otros/QuantitySelector.jsx";
import { HOME } from "../../utils/const/navigatorConst.js";
import { getSecureStoreData } from "../../utils/gettersAndSetters/getters.js";
import { SHOW_PRICE_WITH_TAX } from "../../utils/const/secureStoreConst.js";
import PdfTabNavigator from "../otros/pdfView/PdfTabNavigator.jsx";
import ListadoPedidos from "../pedidos/ListadoPedidos.jsx";

const PedidosComercialScreenView = (props) => {
  const [clientProducts, setClientProducts] = useState([]);
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState(new PdaUser());
  const [globalState, setGlobalState] = useGlobalContext();
  const [searchText, setSearchText] = useState("");
  const selectedClientId = props.cliente.client;
  const [showAllProducts, setShowAllProducts] = useState(false);
  const [showCobros, setShowCobros] = useState(false);
  const [allProducts, setAllProducts] = useState([]);
  const [quantities, setQuantities] = useState({});
  const [isQuantityModalVisible, setQuantityModalVisible] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [isPurchaseModalVisible, setPurchaseModalVisible] = useState(false);
  const [totalPurchase, setTotalPurchase] = useState(0);
  const [showFinalizeOptionsModal, setShowFinalizeOptionsModal] =
    useState(false);
  const [internetState, setInternetState] = useInternetContext();
  const [showPriceWithTax, setShowPriceWithTax] = useState(false);
  const [visibleData, setVisibleData] = useState([]);
  const [pdfUrls, setPdfUrls] = useState([]);
  const [pendingPayments, setPendingPayments] = useState([]);
  const [isPendingPaymentsModalVisible, setPendingPaymentsModalVisible] =
    useState(false);
  const itemsPerPage = 10;
  const [page, setPage] = useState(1);

  var DEV = new PedidosComercialLogic({
    clientProducts,
    setClientProducts,
    products,
    setProducts,
    setLoading,
    setUser,
    user,
    setGlobalState,
    globalState,
    selectedClientId,
  });

  useEffect(() => {
    async function fetchData() {
      const showPriceWithTax = await getSecureStoreData(SHOW_PRICE_WITH_TAX);
      setShowPriceWithTax(showPriceWithTax === "true");
      await DEV.init();
      if (internetState.isConnected) {
        try {
          await DEV.getProductsByOrders(props.cliente.client);
          await DEV.getProducts();
        } catch (error) {
          console.error("Error al cargar clientes:", error);
        }
      } else {
        try {
          await DEV.getLocalProductsByOrders();
          await DEV.getLocalProducts();
        } catch (error) {
          console.error("Error al cargar clientes:", error);
        }
      }

      try {
        const totalDue = await DEV.getTotalDueByClient(props.cliente.client);
        setPendingPayments(totalDue);
        setPendingPaymentsModalVisible(true);
      } catch (error) {
        console.error("Error fetching total due:", error);
        Alert.alert("Error", "Problemas al obtener los pagos pendientes.");
      }
    }
    fetchData();
  }, []);

  useEffect(() => {
    mergeProducts(clientProducts, products);
  }, [products, clientProducts]);

  useEffect(() => {
    setVisibleData(filteredProducts.slice(0, itemsPerPage));
    setPage(1);
  }, [allProducts, showAllProducts, filteredProducts]);

  useEffect(() => {
    const filtered = allProducts.filter(
      (product) =>
        (product.label || "")
          .toLowerCase()
          .includes(searchText.toLowerCase()) &&
        (showAllProducts ? product.client === 0 : product.client === 1)
    );
    setVisibleData(filtered.slice(0, itemsPerPage));
    setPage(1);
  }, [searchText, allProducts, showAllProducts]);

  const loadMoreData = () => {
    const filtered = allProducts.filter(
      (product) =>
        (product.label || "")
          .toLowerCase()
          .includes(searchText.toLowerCase()) &&
        (showAllProducts ? product.client === 0 : product.client === 1)
    );
    const startIndex = page * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const newData = filtered.slice(startIndex, endIndex);

    setPage(page + 1);
    setVisibleData((prevData) => [...prevData, ...newData]);
  };

  const mergeProducts = async (clientProducts, products) => {
    const productMap = new Map();
    products.forEach((product) => {
      if (product.fkProduct != null) {
        productMap.set(product.fkProduct, {
          ...product,
          client: 0,
          quantity: 0,
          productStock: product.productStock || 0,
        });
      }
    });

    clientProducts.forEach((product) => {
      if (product.fkProduct != null) {
        const existingProduct = productMap.get(product.fkProduct);
        if (existingProduct) {
          productMap.set(product.fkProduct, {
            ...existingProduct,
            ...product,
            productStock:
              product.productStock || existingProduct.productStock || 0,
            client: 1,
          });
        } else {
          productMap.set(product.fkProduct, {
            ...product,
            client: 1,
            productStock: product.productStock || 0,
          });
        }
      }
    });

    const arrayMerge = Array.from(productMap.values());
    setAllProducts(arrayMerge);

    if (internetState.isConnected) {
      await DEV.saveProductsLocal(arrayMerge);
    }

    setLoading(false);
  };

  const handleSearch = (text) => {
    setSearchText(text);
  };

  const toggleProductList = () => {
    setLoading(true);
    setShowAllProducts(!showAllProducts);
    setLoading(false);
  };

  const addProductToClient = (product) => {
    setSelectedProduct(product);
    setQuantityModalVisible(true);
  };

  const handleQuantitySave = (quantity, subprice, discount) => {
    console.log("CANTIDAD", subprice)
    setQuantities((prevQuantities) => ({
      ...prevQuantities,
      [selectedProduct.fkProduct]: quantity,
    }));

    const updatedClientProducts = clientProducts.map((product) => {
      if (product.fkProduct === selectedProduct.fkProduct) {
        return {
          ...product,
          quantity,
          subprice: subprice,
          remise_percent: discount,
          client: 1,
        };
      }
      return product;
    });

    if (
      !updatedClientProducts.find(
        (product) => product.fkProduct === selectedProduct.fkProduct
      )
    ) {
      updatedClientProducts.push({
        ...selectedProduct,
        quantity,
        subprice: subprice,
        remise_percent: discount,
        client: 1,
      });
    }

    setClientProducts(updatedClientProducts);
    mergeProducts(updatedClientProducts, products);
    setQuantityModalVisible(false);
  };

  const removeProductFromClient = (fkProduct) => {
    setLoading(true);

    const remainingClientProducts = clientProducts.filter(
      (product) => product.fkProduct !== fkProduct
    );
    const updatedProducts = products.map((product) => {
      if (product.fkProduct === fkProduct) {
        return { ...product, client: 0, quantity: 0 };
      }
      return product;
    });

    setClientProducts(remainingClientProducts);
    setProducts(updatedProducts);
    mergeProducts(remainingClientProducts, updatedProducts);
    setLoading(false);
  };

  const handleQuantityChange = (fkProduct, newQuantity) => {
    setQuantities((currentQuantities) => ({
      ...currentQuantities,
      [fkProduct]: newQuantity,
    }));

    if (newQuantity === 0) {
      removeProductFromClient(fkProduct);
    } else {
      const updatedClientProducts = clientProducts.map((product) =>
        product.fkProduct === fkProduct
          ? { ...product, quantity: newQuantity }
          : product
      );
      setClientProducts(updatedClientProducts);
      mergeProducts(updatedClientProducts, products);
    }
  };

  const filteredProducts = allProducts.filter(
    (product) =>
      (product.label || "").toLowerCase().includes(searchText.toLowerCase()) &&
      (showAllProducts ? product.client === 0 : product.client === 1)
  );

  const countProductsWithQuantity = () => {
    return allProducts.filter(
      (product) => product.client === 1 && quantities[product.fkProduct] > 0
    ).length;
  };

  const calculateTotalPurchase = () => {
    return allProducts
      .reduce((acc, product) => {
        if (product.client === 1 && quantities[product.fkProduct]) {
          const priceWithDiscount =
            product.subprice * (1 - product.remise_percent / 100);

          return acc + priceWithDiscount * quantities[product.fkProduct];
        }
        return acc;
      }, 0)
      .toFixed(2);
  };

  const finalizePurchase = async () => {
    let filteredProducts = allProducts.filter(
      (product) =>
        product.client === 1 &&
        !Number.isNaN(parseInt(product.quantity)) &&
        parseInt(product.quantity) > 0 &&
        product.fkProduct != null
    );
  
    let pdfUrlsArray = [];
  
    if (!internetState.isConnected) {
      await DEV.saveOrderLocally(props.cliente.clientId, filteredProducts, 0);
      success = true;
    } else {
      if (props.cliente.client != null) {
        const totalPurchase = filteredProducts.reduce(
          (acc, product) =>
            acc + parseFloat(product.price) * parseInt(product.quantity),
          0
        );
        setTotalPurchase(totalPurchase.toFixed(2));
  
        const response = await DEV.createOrderFromClient(
          props.cliente.client,
          filteredProducts.map(product => ({
            ...product,
            price: parseFloat(product.price)  // Ensure the price is always multiprices["1"]
          })),
          0
        );
  
        if (response) {
          pdfUrlsArray.push(response);
        } else {
          console.error(
            "Error al realizar la compra:",
            response.error
          );
        }
      } else {
        console.log("El ID del cliente es nulo.");
      }
    }
  
    if (pdfUrlsArray.length > 0) {
      setPdfUrls(pdfUrlsArray);
      setPurchaseModalVisible(true);
    }
  };
  
  

  const calculateProductPrice = (subprice_ttc, subprice, tva_tx, showPriceWithTax) => {
    if (showPriceWithTax) {
      return parseFloat(subprice_ttc).toFixed(2);
    } else {
      return parseFloat(subprice).toFixed(2);
    }
  };

  if(showCobros){
    return <ListadoPedidos cliente={props.cliente}/>
  }

  return (
    <View style={[{ flex: 1, padding: 2 }, globalStyles.container]}>
      <View style={styles.headerContainer}>
        <View style={styles.headerContent}>
          <Icon
            name={showAllProducts ? "arrow-left" : "cart-plus"}
            size={40}
            onPress={toggleProductList}
          />
          <View style={styles.headerTitle}>
            <Text style={styles.headerTitleText}>{props.cliente.name}</Text>
            <Text
              style={styles.headerTitleText}
            >{`TOTAL CARRITO SIN IVA: ${calculateTotalPurchase()} €`}</Text>
          </View>
          {!showAllProducts ? (
            <Icon
              name="content-save"
              size={40}
              onPress={() => setShowFinalizeOptionsModal(true)}
            />
          ) : (
            <Icon
              name="content-save"
              size={40}
              onPress={toggleProductList}
            />
          )}
        </View>
        <View style={styles.buscarStyle}>
          <SearchInput
            placeholder="Buscar producto..."
            onSearch={handleSearch}
          />
        </View>
      </View>
      {loading ? (
        <>
        <ActivityIndicator size="large" />
        </>
        
      ) : (
        <FlashList
          keyboardDismissMode="interactive"
          keyboardShouldPersistTaps="handled"
          data={visibleData}
          renderItem={({ item }) => (
            <TouchableOpacity onPress={() => addProductToClient(item)}>
              <View
                style={[
                  styles.productContainer,
                  {
                    backgroundColor: item.client === 1 ? "#2271b3" : "#FDFD96",
                  },
                ]}
              >
                <View style={styles.productHeader}>
                  <View style={styles.productHeaderTitle}>
                    <Text style={styles.productHeaderText}>{item.label}</Text>
                  </View>
                  <Icon
                    name="calculator"
                    size={50}
                    onPress={() => addProductToClient(item)}
                  />
                </View>
                <View style={styles.containerRow}>
                  <View style={styles.priceContainer}>
                    {!showAllProducts ? (
                      <>
                        <View style={styles.priceColumn}>
                          <Text style={styles.priceText}>
                            Precio histórico{" "}
                            {showPriceWithTax ? "IVA" : "SIN IVA"}:{" "}
                            {`${calculateProductPrice(
                              item.subprice,
                              item.subprice_ttc,
                              item.tva_tx,
                              showPriceWithTax
                            )} €`}
                          </Text>
                        </View>
                        <View style={styles.priceColumn}>
                          {item.realPrice !== 0 ? (
                            <Text style={styles.priceText}>
                              Precio {showPriceWithTax ? "IVA" : "SIN IVA"}:{" "}
                              {`${calculateProductPrice(
                                item.price,
                                item.subprice,
                                item.tva_tx,
                                showPriceWithTax
                              )} €`}
                            </Text>
                          ) : null}
                        </View>
                      </>
                    ) : (
                      <>
                        <Text style={styles.priceText}>
                          Precio venta {showPriceWithTax ? "IVA" : "SIN IVA"}:{" "}
                          {`${calculateProductPrice(
                            item.subprice,
                            item.subprice,
                            item.tva_tx,
                            showPriceWithTax
                          )} €`}
                        </Text>
                      </>
                    )}
                    <Text style={styles.priceText}>
                      Precio Total:{" "}
                      {`${
                        (
                          parseFloat(item.subprice || 0) *
                          (quantities[item.fkProduct] || 0) *
                          (1 - parseFloat(item.remise_percent || 0) / 100)
                        ).toFixed(2) || 0
                      } €`}
                    </Text>
                    <Text style={styles.priceText}>
                      Stock actual: {item.productStock || 0}
                    </Text>
                  </View>
                  <View style={styles.stockContainer}>
                    <Text style={styles.stockText}>
                      Unidades/caja: {item.options_unidades || 0}
                    </Text>
                    <Text style={styles.stockText}>
                      Unidades : {quantities[item.fkProduct] || 0} uds 
                    </Text>
                    {!showAllProducts ? (
                      <Text style={styles.stockText}>
                        Descuento: {item.remise_percent || 0}%
                      </Text>
                    ) : (
                      <></>
                    )}
                  </View>
                </View>
              </View>
            </TouchableOpacity>
          )}
          keyExtractor={(item) => item.fkProduct.toString()}
          onEndReached={loadMoreData}
          onEndReachedThreshold={0.1}
          estimatedItemSize={200}
          threshold={5}
        />
      )}
      <View style={styles.footerContainer}>
        <Text
          style={styles.footerText}
        >{`Productos seleccionados: ${countProductsWithQuantity()}`}</Text>
      </View>
      <Modal
        animationType="slide"
        transparent={true}
        visible={isQuantityModalVisible}
        onRequestClose={() => setQuantityModalVisible(!isQuantityModalVisible)}
      >
        <QuantitySelector
          isVisible={isQuantityModalVisible}
          onClose={() => setQuantityModalVisible(false)}
          onSave={handleQuantitySave}
          product={selectedProduct}
          showPriceWithTax={showPriceWithTax} 

        />
      </Modal>
      <Modal
        animationType="slide"
        transparent={true}
        visible={showFinalizeOptionsModal}
        onRequestClose={() => setShowFinalizeOptionsModal(false)}
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>
              FINALIZACIÓN DEL PEDIDO
            </Text>
            <Button
              buttonStyle={styles.buttonStyle}
              title="Crear pedido completo"
              onPress={() => {
                finalizePurchase(false);
                setShowFinalizeOptionsModal(false);
              }}
            />
            <Button
              buttonStyle={styles.buttonStyle}
              title="Cancelar"
              onPress={() => setShowFinalizeOptionsModal(false)}
            />
          </View>
        </View>
      </Modal>
      <Modal
        animationType="slide"
        transparent={true}
        visible={isPurchaseModalVisible}
        onRequestClose={() => setPurchaseModalVisible(false)}
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>Pedido creado correctamente</Text>
            <Text style={styles.modalSubTitle}>
              Total: €{calculateTotalPurchase()}
            </Text>
            {/* {pdfUrls.length > 0 &&
              (console.log("VEAMOS si hay pdfs o no", pdfUrls),
              (<PdfTabNavigator pdfUrls={pdfUrls} />))} */}
            <Button
              buttonStyle={styles.buttonStyle}
              title="Ver cobros"
              onPress={() => {
                setPurchaseModalVisible(false);
                props.navigation.navigate("NuevaPantalla"); 
              }}
            />
            <Button
              buttonStyle={styles.buttonStyle}
              title="Home"
              onPress={() => {
                setPurchaseModalVisible(false);
                RootNavigation.navigate(HOME);
              }}
            />
          </View>
        </View>
      </Modal>
      <Modal
        animationType="slide"
        transparent={true}
        visible={isPendingPaymentsModalVisible}
        onRequestClose={() => setPendingPaymentsModalVisible(false)}
      >
        <View style={modalStyles.modalContainer}>
          <View style={modalStyles.modalContent}>
            <Text style={modalStyles.modalTitle}>PAGOS PENDIENTES</Text>
            {pendingPayments.total_due > 0 ? (
                <View>
                  <Text style={modalStyles.modalSubTitle}>
                    TOTAL : €{pendingPayments.total_due.toFixed(2) }
                  </Text>
                </View>
            ) : (
              <Text style={modalStyles.modalSubTitle}>
                No hay pagos pendientes.
              </Text>
            )}
            <Button
              buttonStyle={modalStyles.buttonStyle}
              title="Ver cobros"
              onPress={() => setShowCobros(true)}
            />
            <Button
              buttonStyle={modalStyles.buttonStyle}
              title="Cerrar"
              onPress={() => setPendingPaymentsModalVisible(false)}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

export default PedidosComercialScreenView;

Quantity selector

import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  Button,
  Modal,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  KeyboardAvoidingView,
  Platform,
  TouchableWithoutFeedback,
  Keyboard
} from "react-native";
import { getSecureStoreData } from "../../utils/gettersAndSetters/getters.js"; // Asegúrate de que la ruta sea correcta
import { SHOW_PRICE_WITH_TAX } from "../../utils/const/secureStoreConst.js";

const QuantitySelector = ({ isVisible, onClose, onSave, product }) => {
  const [quantity, setQuantity] = useState("0");
  const [unitType, setUnitType] = useState("units"); // 'units' or 'pack'
  const [unitsPerPack, setUnitsPerPack] = useState(1);
  const [price, setPrice] = useState('0.00');
  const [discount, setDiscount] = useState("0");
  const [showPriceWithTax, setShowPriceWithTax] = useState(false);

  useEffect(() => {
    const fetchShowPriceWithTax = async () => {
      const showPriceWithTax = await getSecureStoreData(SHOW_PRICE_WITH_TAX);
      setShowPriceWithTax(showPriceWithTax === "true");
    };

    fetchShowPriceWithTax();

    if (product && product.options_unidades) {
      setUnitsPerPack(product.options_unidades);
    }
    if (product) {
      if (showPriceWithTax) {
        setPrice(parseFloat(product.subprice_ttc).toFixed(2));
      } else {
        setPrice(parseFloat(product.subprice).toFixed(2));
      }
    }
  }, [product, showPriceWithTax]);

  const handleSave = () => {
    const finalQuantity =
      unitType === "pack"
        ? parseInt(quantity, 10) * unitsPerPack
        : parseInt(quantity, 10);
    const finalPrice = parseFloat(price).toFixed(2);
    const finalDiscount = parseFloat(discount).toFixed(2);
    onSave(finalQuantity, finalPrice, finalDiscount);
  };

---

  const handleNumberPress = (number) => {
    setQuantity((prevQuantity) =>
      prevQuantity === "0"
        ? number.toString()
        : prevQuantity + number.toString()
    );
  };

  const handleClear = () => {
    setQuantity("0");
  };

  const handleBackspace = () => {
    setQuantity((prevQuantity) =>
      prevQuantity.length > 1 ? prevQuantity.slice(0, -1) : "0"
    );
  };

  const handlePriceChange = (text) => {
    const parsed = text.replace(/[^0-9.]/g, "");
    setPrice(parsed);
  };

  const handleDiscountChange = (text) => {
    const parsed = text.replace(/[^0-9.]/g, "");
    setDiscount(parsed);
  };

  return (
    <Modal visible={isVisible} transparent={true} animationType="slide">
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.modalContainer}
      >
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
          <View style={styles.modalContent}>
            <Text style={styles.productText}>Producto {product?.label}</Text>
            <View style={styles.switchContainer}>
              <TouchableOpacity
                style={[
                  styles.switchButton,
                  unitType === "units" ? styles.active : styles.inactive,
                ]}
                onPress={() => setUnitType("units")}
              >
                <Text style={styles.switchText}>Unidades</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  styles.switchButton,
                  unitType === "pack" ? styles.active : styles.inactive,
                ]}
                onPress={() => setUnitType("pack")}
              >
                <Text style={styles.switchText}>Envases</Text>
              </TouchableOpacity>
            </View>
            <Text style={styles.quantityDisplay}>{quantity}</Text>
            <View style={styles.calculatorContainer}>
              {[1, 2, 3, 4, 5, 6, 7, 8, 9, 0].map((number) => (
                <TouchableOpacity
                  key={number}
                  style={styles.calculatorButton}
                  onPress={() => handleNumberPress(number)}
                >
                  <Text style={styles.calculatorButtonText}>{number}</Text>
                </TouchableOpacity>
              ))}
              <TouchableOpacity
                style={styles.calculatorButton}
                onPress={handleBackspace}
              >
                <Text style={styles.calculatorButtonText}>⌫</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.calculatorButton}
                onPress={handleClear}
              >
                <Text style={styles.calculatorButtonText}>CE</Text>
              </TouchableOpacity>
            </View>
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>
                Precio de venta {showPriceWithTax ? "CON IVA" : "SIN IVA"}:
              </Text>
              <TextInput
                style={styles.input}
                keyboardType="numeric"
                value={price}
                onChangeText={handlePriceChange}
                placeholder="0.00"
                placeholderTextColor="#aaa"
                clearButtonMode="always"
              />
            </View>
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>Descuento (%):</Text>
              <TextInput
                style={styles.input}
                keyboardType="numeric"
                value={discount}
                onChangeText={handleDiscountChange}
                placeholder="0"
                placeholderTextColor="#aaa"
                clearButtonMode="always"
              />
            </View>
            <View style={styles.buttonContainer}>
              <Button title="Guardar" onPress={handleSave} />
              <Button title="Cancelar" onPress={onClose} />
            </View>
          </View>
        </TouchableWithoutFeedback>
      </KeyboardAvoidingView>
    </Modal>
  );
};
export default QuantitySelector;

Fetch API: TypeError: Cannot read properties of null (reading ‘getReader’) [duplicate]

I am trying to use fetch API as:

fetch(".../data", {mode: 'no-cors'})
  // Retrieve its body as ReadableStream
  .then((response) => {
    const reader = response.body.getReader();
    // read() returns a promise that resolves when a value has been received
    reader.read().then(function pump({ done, value }) {
      if (done) {
        // Do something with last chunk of data then exit reader
        return;
      }
      // Otherwise do something here to process current chunk
      console.log(value);

      // Read some more, and call this function again
      return reader.read().then(pump);
    });
  })
  .catch((err) => console.error(err));

When I hit url in browser, results are fetched.

But with above code, I see error:

TypeError: Cannot read properties of null (reading 'getReader')

What am I missing here?

Dont know how to fetch data from mongoDB and display it in nextjs app using mongoose

So like, im making an app using nextjs, where i take input from user (username password and email) from home page, save it to db via mongoose and then display it on other page named dashboard, im able to save data in db as its easy, but i dont know how to fetch it from db and display it in dashboard in div.. the sources on internet are too confusing and gpt isnt helpful at all..

this is my app structureenter image description here

this is my models/inputs.js

import mongoose from "mongoose";
const inputInfo = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
})

const Info=mongoose.models.Info || mongoose.model('Info',inputInfo);

export default Info

this is my action/inputs.js

"use server"
import mongoose from "mongoose";
import Info  from "../models/inputs";

const getInputs = async (e) => {
    await mongoose.connect("mongodb://localhost:27017/logininfo");
    if(mongoose.connection.readyState === 1) {
        console.log("connected");
    }else{
        console.log("not connected");
    }

    const username = e.get("username");
    const email = e.get("email");
    const password = e.get("password");
    const data = {
        username,
        email,
        password
    }
    console.log(data);
    const userExists= await Info.findOne({username});
    if(userExists) {
        console.log("user exists");
    }else{
        const newUser = new Info(data);
        await newUser.save();
        console.log("new user created");
    }
}

export default getInputs;

this is my api/fetchInfo.js

// api/fetchinfo.js
"use server"

import mongoose from "mongoose";
import express from 'express';
import bodyParser from 'body-parser';
import Info from '../models/input';

const app = express();
const port = 3000;

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Middleware to handle CORS
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// Route to fetch information
app.get('mongodb://localhost:27017/logininfo', async (req, res) => {
    await mongoose.connect("mongodb://localhost:27017/logininfo");
    if(mongoose.connection.readyState === 1) {
        console.log("connected");
    } else {
        console.log("not connected");
    }
  
});
app.post('mongodb://localhost:27017/logininfo', async (req, res) => {
    await mongoose.connect("mongodb://localhost:27017/logininfo");
    if(mongoose.connection.readyState === 1) {
        console.log("connected");
    } else {
        console.log("not connected");
    }
    
    try {
        const data = await Info.create(req.body);
        res.json(data);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
})

// Start the server
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

this is my dashboard/page.js

// app/dashboard/page.js
"use client"
import React, { useState, useEffect } from 'react';

const Dashboard = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    useEffect(() => {
        setLoading(true);
        fetch("http://localhost:3000/api/fetchinfo")
            .then((res) => {
                if (!res.ok) {
                    throw new Error('Network response was not ok');
                }
                return res.json();
            })
            .then((data) => {
                setData(data);
                setLoading(false);
            })
            .catch((error) => {
                setError(error);
                setLoading(false);
            });
    }, []);

    if (loading) {
        return <p>Loading...</p>;
    }

    if (error) {
        return <p>Error: {error.message}</p>;
    }

    return (
        <div>
            {data ? data.map((item, index) => (
                <p key={index}>{item.username} - {item.email}</p>
            )) : <p>No data found</p>}
        </div>
    );
}

export default Dashboard;

i was expecting it to display data but sadly it didnt work, im able to save it properly but displaying is 🙁

How to focus on ChatGPT prompt text area using JavaScript?

The ChatGPT Web interface has a with id “prompt-textarea”enter image description here in which users input their prompts to get a response. Normally I would drag my cursor to the text area and click on it to focus it, but now I want to do this using (preferably plain) JavaScript.

I have tried document.getElementById("prompt-textarea").focus(); but that returns undefined and doesn’t focus on the text area, I still have to manually drag my cursor and click. To reproduce, visit chatgpt.com, click anywhere on the page to unfocus the text area, go to the console and type document.getElementById("prompt-textarea").focus();, you’ll notice that it will remain unfocused (and return undefined). I’ve observed this behavior on both Firefox and Brave.

Handling tables in quill

I’m trying to use tables with the Quill WYSIWYG editor. I’m trying to do it in the sandbox: https://quilljs.com/playground/snow . I’ve added ['table'] to the toolbar, so now it looks like this:

const quill = new Quill('#editor', {
  modules: {
    toolbar: [
      [{ header: [1, 2, false] }],
      ['bold', 'italic', 'underline'],
      ['image', 'code-block'],
      ['table']
    ],
  },
  placeholder: 'Compose an epic...',
  theme: 'snow', // or 'bubble'
});

The table icon appeared, however I have no freakin’ idea on how to add columns and rows to it. Does anyone know?

Not able to launch desktop electron js app using playwright

I’m attempting to use playwright to automate an electron js application but unfortunately the executable path that i am providing is not targeting the app and when i am providing the path to different electron js app(slack) it is launching the app. little help would be highly appreciated.

this is the code for it –

import { test, expect, type Page } from ‘@playwright/test’;
import { _electron as electron, ElectronApplication } from ‘playwright’;

test(‘get started’, async ({ page }) => {
// test.setTimeout(150000);
let electronApp: ElectronApplication =
await electron.launch({

        executablePath: 'path to my electron js app '
      
});

How to iterate the sequence of for(let i=0;i<n;i++){arr.splice(arr.length/2,0,i);} (eg:n=6 : 1,3,5,4,2,0), but not create arr first?

For example, I have some sequence that comes from pushing indexes to an array into middle contineously:

const n=6;
const arr=[];
for(let i=0;i<n;i++){
  arr.splice(arr.length/2,0,i);
}
document.writeln(arr.join(" "));

which the result is 1 3 4 2 0.

But now I want a loop that iterates the indexes above, but not creating an index array first. How to I write that loop?

I tried:

const n=6;
for(let i=0;i<n;i++){
  let index=null;
  if(i==Math.floor(n/2)){
    index=n-1;
  }else if(i<n/2){
    index=1+2*i;
  }else{
    index=2*(n-i-1);
  }
  document.write(index+" ");
}

but the result is 1 3 5 5 2 0 instead of 1 3 5 4 2 0. How to correct the loop (Or other built-in methods like reduce() that can have simpler lines of codes as solutions?)?

Is it valid to place a hook inside and call it from within there?

VSCode doesn’t mark this as invalid, despite the hooks being conditionally run:

function useHook() {
    return 1;
}
function useHook2() {
    const two = useMemo(() => 2, []);
    return two;
}

const hookDictionary = {
    useHook,
    useHook2
}

export function HookUser(index) { 
    let func = hookDictionary[index];
    func();
    return null;
}

Is this intentional, and considered valid?
Is it being hidden by the use of hookDictionary?
My assumption is that this is the case, since it’s functionally the same as:

export function HookUser(index: string) { 
    let func = hookDictionary[index];
    if(index === 'useHook') {
        useHook();
    }
    else if(index === 'useHook2') {
        useHook2();
    }
    return null;
}

Which does throw an error.

How do I override React-Selects native styles with my own?

I am new to React and not quite sure how some plugins/components handle CSS.

I am aware of how to use the styleNames prop with the React Select component. However, I want to use it to inject existing utility classes from my site’s existing .css file. I can do this, as per below, but this adds my classes alongside React Select’s default classes and React Select’s default classes override mine.

For example, if I set singleValue color class to be my .color-primary utility class, as such:

<Select 
      onChange={(selectedOption) => onChange({ name: name, value: selectedOption.value }, true)}
      options={options}
      classNames={{
        singleValue: () => 'color-primary',
      }}
      name={name}
    />

The HTML I get for that element is:

<div class="color-primary css-1dimb5e-singleValue">Option 1</div>

Which is fine, but the color specified in .css-1dimb5e-singleValue, which seems to come from a <style> tag injected at the bottom of <head> overrides the color specified in .color-primary which appears in my normal .css file higher up in the <head>.

I know I could use specificity (eg .my-select .color-primary) or create my own SCSS file for my component, but I’d rather just use my existing utility classes already in the site for now.

Would anyone know of a way around this?

React Native Expo App crashes on Testflight when it starts up

When I published my build to the app store and tried to run it on TestFlight it immediately crashes. I have no idea where to look on how to fix the crash. The app runs smoothly when starting it in development mode, production mode, or regular expo go. (I do not have a macbook or mac, I solely use windows!) I took a look at the crash logs which were given but it all looks like a bunch of gibberish!

SVG.js addTo() cannot find target DOM on Svelte

I wanted to add a simple SVG example that is manipulatable with SVG.js

I tried this.

<main>
    <section class="center">
        <h1>Hello!</h1>
        <p>This is project page.</p>
    </section>
    <section id="canvas">
        <canvas></canvas>
    </section>
</main>

<script>
    import { SVG } from '@svgdotjs/svg.js';
    var draw = SVG().addTo("#canvas").size(300, 300)
    var rect = draw.rect(100, 100).attr({ fill: '#f06' })
       
</script>

but it prints out this error on browser console:

TypeError: Cannot read properties of null (reading 'put')
    at Svg.addTo (@svgdotjs_svg__js.js?t=1722923695034&v=5d11dd42:1846:32)
    at instance (index.svelte:13:22)
    at init (chunk-5CD65IUO.js?v=5d11dd42:2137:23)
    at new Project (index.svelte:14:55)
    at createComponent (svelte-hooks.js?v=5d11dd42:206:20)
    at targetCmp.$replace (svelte-hooks.js?v=5d11dd42:269:15)
    at refreshComponent (proxy.js?v=5d11dd42:171:15)
    at ProxyAdapterDom.rerender (proxy-adapter-dom.js?v=5d11dd42:77:5)
    at proxy.js?v=5d11dd42:408:9
    at Array.forEach (<anonymous>)

It seemed that Svg.addTo() method cannot find the targetDOM.
I thouth it was the problem of DOM load timing, so I tried this:

<main>
    <section class="center">
        <h1>Hello!</h1>
        <p>This is project page.</p>
    </section>
    <section id="canvas">
        <canvas></canvas>
    </section>
</main>

<script>
    import { SVG } from '@svgdotjs/svg.js';

document.addEventListener("DOMContentLoaded",()=>{
    var draw = SVG().addTo("#canvas").size(300, 300)
    var rect = draw.rect(100, 100).attr({ fill: '#f06' })
});
</script>

And… nothing happens. No errors, no logs. Seems like ‘DOMContentLoaded’ event is never fired in svelte? Can anyone help me implementing SVG.js on vite+svelte app?

Why accessing a components root element using this.$(#rootElementId) returns zero elements?

DOM

<div id="ember3705" class="ember-view">
<div id='childelement'></div>
</div>

I’m trying to execute this js code this.$('#ember3705') in component.js of the above component after it has been rendered. But it gives me zero elements as result below:

context: div#ember3705.ember-view
length: 0
prevObject: jQuery.fn.init
0: div#ember3705.ember-view
context: div#ember3705.ember-view
length: 1
[[Prototype]]: Object
selector: “#ember3705”

I’ve tried another code this.$(), this gives me the desired below result,

0: div#ember3705.ember-view
context: div#ember3705.ember-view
length: 1

My doubt is why this.$('#ember3705') gives me with no results whereas this.$() gives me results. Is this the behaviour of ember or am i missing out something?