How to Include Filename in Image Labels Using Lightbox2

I’m using Lightbox2 for displaying images in a gallery and would like to include the filename in the image label along with the image number and total count. By default, Lightbox2 allows customization of the label to show the image number and total using the albumLabel option in the format “Image %1 of %2”. I want to modify this to also show the filename of the image being viewed, e.g., “Image %1 of %2 – filename.jpg” just without the .jpg .

Here is the relevant part of my current Lightbox2 setup:

Lightbox.defaults = {
    albumLabel: 'Image %1 of %2',
    ...
};

Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
    return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
};

I’ve tried modifying the albumLabel to include a placeholder for the filename and adjusting the imageCountLabel method to replace it with the actual filename, but it’s not working as expected. Here’s what I’ve attempted:

Lightbox.defaults = {
    albumLabel: 'Image %1 of %2 - %3', // Added %3 for filename
    ...
};

Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages, filename) {
    return this.options.albumLabel
           .replace(/%1/g, currentImageNum)
           .replace(/%2/g, totalImages)
           .replace(/%3/g, filename);
};

Could anyone help me correct this setup or suggest a better way to include the filename in the image label?

Next.js : Performance Issues with Large Codebase Using App Router

I’m experiencing significant performance issues with my Next.js application. My project has grown substantially, and the build times and page loads have become noticeably slower. Here are the details of my setup:

Next.js Version: 15rc
Router: App Router
Codebase Size: Large with multiple complex pages and components

Problems:

Build Times: The build times have increased drastically as the codebase has grown.
Page Loads: Initial page loads are slow, and navigating between pages isn't as smooth as expected.

What I’ve Tried:

Code Splitting: I've implemented dynamic imports for some components, but the improvements are marginal.
Caching: Enabled server-side caching, but it hasn't significantly reduced the load times.
Analysis Tools: Used Webpack Bundle Analyzer to identify large bundles, but refactoring them hasn't helped much.
Optimization Tips: Followed various optimization tips from the Next.js documentation, but the performance gains are minimal.

Questions:

Are there specific configurations or best practices in Next.js 15rc that are particularly effective for large codebases?
How can I optimize the App Router for better performance in a large application?
Are there any known issues with Next.js 15rc that could be contributing to these performance problems?
Would upgrading to a stable release (if available) improve performance, or are there other recommended strategies?

Any advice or guidance on how to tackle these performance issues would be greatly appreciated!

Thank you!

DoesNotExist at /cart/cart_add/ product = Products.objects.get(id=product_id) product_id = None

My problem: DoesNotExist at /cart/cart_add/
When I try get product_id in request.POST
it`s value = None

Learn django but don`t now JS.
Perhaps:
Mistake in JS file
This code work with django4 (use django5)

jquery-ajax.js

$(document).ready(function () {
    var successMessage = $("#jq-notification");
    $(document).on("click", ".add-to-cart", function (e) {
        e.preventDefault();
        var goodsInCartCount = $("#goods-in-cart-count");
        var cartCount = parseInt(goodsInCartCount.text() || 0);
        var product_id = $(this).data("product-id");
        var add_to_cart_url = $(this).attr("href");
        $.ajax({
            type: "POST",
            url: add_to_cart_url,
            data: {
                product_id: product_id,
                csrfmiddlewaretoken: $("[name=csrfmiddlewaretoken]").val(),
            },
            success: function (data) {
                successMessage.html(data.message);
                successMessage.fadeIn(400);              
                setTimeout(function () {
                    successMessage.fadeOut(400);
                }, 7000);
                cartCount++;
                goodsInCartCount.text(cartCount);
                var cartItemsContainer = $("#cart-items-container");
                cartItemsContainer.html(data.cart_items_html);
            },
            error: function (data) {
                console.log("text");
            },
        });
    });

catalog.html

   
<a href="{% url "cart:cart_add" %}" class="btn add-to-cart" data-product-id="{{ product.id }}">  
{% csrf_token %}
<img class="mx-1" src="{% static "deps/icons/cart-plus.svg" %}" alt="Catalog Icon" width="32" height="32">

views.py

def cart_add(request): 
    
    product_id = request.POST.get("product_id") 
    product = Products.objects.get(id=product_id)
    user_cart = get_user_carts(request)
    cart_items_html = render_to_string(
        "carts/includes/included_cart.html", {'carts': user_cart}, request=request
    )    
    response_data =  {
        'masage': 'Тext', 
        'cart_items_html': cart_items_html, 
    }
    return JsonResponse(response_data) 

Traversal of Binary Tree in Order traversal and start “Reverse Order” if node has no children Javascript

Given a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to left, level by level). Once, node has not children go for parent where it has unvisited children.

     1 
   /   
  2     3
 /    /  
4   5 6    7

First traverse 1,2,4
Now 4 has no children
During back traverse in else part output 4, 2
then it should go to 2, 5

Now, 5 is end. Trace isVisited in parent nodes if any of the child is property isVisited as false.

5,2,1,3

Structure of tree with object array javascript

I was looking for this solution but reverse node traversal not working fine for me. Any suggestion welcome.

Sample data

[
    {
        "id": 15,
        "isVisited": true,
        "parentId": -1,
        "children": [
            {
                "id": 16,
                "isVisited": false,
                "parentId": 15,
                "children": [
                    {
                        "id": 14,
                        "isVisited": false,
                        "parentId": 16,
                        "children": [
                            {
                                "id": 12,
                                "isVisited": false,
                                "parentId": 14,
                                "children": [
                                    {
                                        "id": 13,
                                        "isVisited": false,
                                        "parentId": 12,
                                        "children": [
                                            {
                                                "id": 21,
                                                "isVisited": false,
                                                "parentId": 13
                                            },
                                            {
                                                "id": 20,
                                                "isVisited": false,
                                                "parentId": 13
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "id": 3,
                                "isVisited": false,
                                "parentId": 14,
                                "children": [
                                    {
                                        "id": 1,
                                        "isVisited": false,
                                        "parentId": 3,
                                        "children": [
                                            {
                                                "id": 18,
                                                "isVisited": false,
                                                "parentId": 1
                                            },
                                            {
                                                "id": 11,
                                                "isVisited": false,
                                                "parentId": 1
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "id": 2,
                                "isVisited": false,
                                "parentId": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Unable to scroll over a list of items in a container

I have a list of data which i am rendering in a panel, but for some reason i am unable to scroll over it with my mouse scroll wheel,panel has a scrollbar.

I am able to select the scrollbar and slide up and down with it.

.tree-container
{
    padding:10px;
    max-height: 150px;
    overflow-y: scroll;
}
<div class="tree-container">
  <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
 <div class="role-item">Role Items</div>
</div>

In here I am rendering all the items once the data is fetched into a dive with tree-container class and each item in it have role-item class with text in it.

Views
RoleItem.js

    DE.Views.Roles = Common.UI.BaseView.extend(_.extend({
        el: '#left-panel-roles',

        template: _.template([
            '<div class="role-box layout-ct vbox">',
                '<div class="role-header">Roles',
                '<div class="role-btn-close"></div>',
                '</div>',
                '<div class="search-body">',
                    '<div class="search-container">',
                        '<input type="text" name="" spellcheck="false" class="form-control " placeholder="Search" data-hint="1" data-hint-direction="left" data-hint-offset="small">',
                    '</div>',
                    '<div class="options">',
                        '<label><input type="checkbox" class="chk-multi-select"><span>Multi Select</span></label>',
                        '<label><input type="checkbox" class="chk-unmapped"><span>Unmapped</span></label>',
                        '<label><input type="checkbox" class="chk-reorder"><span>Reorder</span></label>',
                    '</div>',
                '</div>',
                '<ul class="roles-list"></ul>',
            '</div>'
        ].join('')),

        renderTreeNode: function ($parent, nodes) {
            let me = this;
            nodes.forEach(node => {
                let $li = $('<li>')
                    .attr('data-id', node.id)
                    .addClass('role-item')
                    .append($('<span>').addClass('item-text').text(node.text));

                if (node.children && node.children.length > 0) {
                    $li.addClass('has-children');
                    let $childList = $('<ul>').addClass('child-list').hide();
                    me.renderTreeNode($childList, node.children);
                    $li.append($childList);
                }

                $li.attr('draggable', 'true');
                $parent.append($li);
            });
        },

    }, DE.Views.Roles || {}));

Controller
RoleItem.js

    DE.Controllers.Roles = Backbone.Controller.extend(_.extend({
        models: [],
        collections: ['Roles'],
        views: ['Roles'],

        onLaunch: function () {
            this.api = this.getApplication().getController('Viewport').getApi();
            this.panelRoles = this.createView('Roles');
            this.panelRoles.on('render:after', _.bind(this.onAfterRender, this));
            this._isDisabled = false;
            this.fetchRolesData();
        },

        fetchRolesData: function () {
            let me = this;
            this.api.fetchRolesTree(function (data) {
                me.fetchedRolesTree = data;
                me.renderTree();
            });
        },

        initTree: function () {
            this.$list = $('.roles-list', this.$el);
            this.$list.empty();
            this.$list.append('<div class="tree-container"></div>');
            this.$treeContainer = this.$list.find('.tree-container');
            this.showLoading();
        },

        renderTree: function () {
            if (!this.fetchedRolesTree) return;

            this.hideLoading();
            this.$treeContainer.empty();
            this.renderItems(this.fetchedRolesTree, this.$treeContainer);
            this.bindTreeEvents();
        },

        renderItems: function (items, $parent) {
            items.forEach(item => {
                let $item = $('<div class="role-item" data-id="' + item.id + '"></div>');
                $item.append('<span class="item-text">' + item.text + '</span>');
                if (item.children && item.children.length > 0) {
                    $item.addClass('has-children');
                    let $childContainer = $('<ul style="display:none;"></ul>');
                    this.renderItems(item.children, $childContainer);
                    $item.append($childContainer);
                }
                $parent.append($item);
            });
        },

        bindTreeEvents: function () {
            let me = this;
            this.$treeContainer.on('click', '.role-item > .item-text', function (e) {
                if (!$(e.target).hasClass('drag-handle') && !me.dragState.active) {
                    e.stopPropagation();
                    let $item = $(this).closest('.role-item');
                    $item.toggleClass('expanded');
                    $item.children('ul').slideToggle(200);
                    me.onSelectItem($item.data('id'), $(this).text());
                }
            });
        },

       //  other code
    }, DE.Controllers.Roles || {}));

Style for role items

.roles-list {
    list-style-type: none;
    padding-left: 0;
    height: calc(100% - 120px); /* Adjust based on your header and search heights */
    overflow-y: auto;
    position: relative;
    -ms-overflow-style: auto;
}


.roles-list ul {
    list-style-type: none;
    padding-left: 20px;
    padding-right: 20px;
}

.roles-list ul:first-child {
    padding-right: 15px;
}

.roles-list-container {
    padding: 10px;
}

/* Tree container */
.tree-container {
    padding: 10px;
    height: 100%;
    max-height: 500px;
    overflow-y: scroll;
    box-sizing: border-box;
}

I should be able to scroll with my mousewheel over the list of items in my panel.

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 '
      
});