How can I get an access to removeBtn without unnecessarily invoking renderBook() function this code? (vanilla JS)

I’m a beginner in programming and I’m making a simple interface where a user can remove the card on a webpage by clicking the remove button.

And now I’m trying to implement this removing functionality.

The whole code is in’test’ branch here, not ‘main’. https://codesandbox.io/p/github/Eveieve/library/test?workspaceId=5fe3d173-5c43-47d3-9b21-7447f2999e60&file=%2Fscript.js&selection=%5B%7B%22endColumn%22%3A2%2C%22endLineNumber%22%3A73%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A59%7D%5D

Currently I have a rendering function where I render elements to the page, including the remove button. Since I want to be able to click that and remove the book, I need an access to the remove button.

Problem is I don’t know how I can get an access to the remove button outside of the rendering function without unnecessarily invoking it (this throws an error, and i’m aware why it’s causing it)

The error is

Uncaught TypeError: Cannot read properties of undefined (reading 'title')
    at renderBook (script.js:44:33)
    at script.js:68:23```
//some code....
  // create removeBtn
  const removeBtn = document.createElement("button");
  removeBtn.classList.add = ("remove-btn", "property");
  removeBtn.textContent = "Remove";
  card.appendChild(removeBtn);

  return { removeBtn };
}

const { removeBtn } = renderBook();

function removeBook(idOfBook) {
  const filteredLibrary = myLibrary.filter((book) => book.id !== idOfBook);
  return { filteredLibrary };
}

I tried to ‘unpack’ removeBtn variable from renerBook() function but since I’m invoking it, the function gets called even before user adds a book so it throws me an error that whatever variable used in the renderBook() is not defined.

How can I get access to the removeBtn without unnecessarily invoking the function?

Or, is it a bad idea to have removeBook function outside the Class? Is it better to have them inside the Class as it’s a functionality that every instance of Book needs?

I separated the functions to make my code more organized but I always encounter this issue of not having access to variables that are scoped to the function. I was wondering if there’s a better way to go about this, or if there’s a fix that can be done to my code.

I’m aware I can just dump everything in the global scope, but I wanted to practice organizing the code better. Let me know if anything’s unclear,appreciate the help.

Error: Chat.find(…).populate(…).populate(…).strictPopulate is not a function

I am trying to populate group chat in mongoose and node and I receive the error that populate is not a function.

I use mongoose 5.12.9

Here the chatModel:

const mongoose = require('mongoose');

const chatModel = mongoose.Schema(
    {
        chatName: { type: String, trim: true },
        isGroupChat: { type: Boolean, default: false },
        users: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User",
            },
        ],
        latestMassage: {
            type: mongoose.Schema.Types.ObjectId,
            // required: false,
            ref: "Message",
        },
        groupAdmin: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
    },
    {
        timestamps: true,
    }
);


const Chat = mongoose.model("Chat", chatModel);

module.exports = Chat;

And then the find that I use:

const asyncHandler = require("express-async-handler");
const Chat = require("../models/chatModel");
// const chatModel = require('../models/chatModel');
const User = require("../models/userModel");

const accessChat = asyncHandler(async (req, res) => {
    const { userId } = req.body;

    if (!userId) {
        console.log("UserId param not sent with request");
        return res.sendStatus(400);
    }

    var isChat = await Chat.find({
        isGroupChat: false,
        $and: [
            { users: { $elemMatch: { $eq: req.user._id } } },
            { users: { $elemMatch: { $eq: userId } } },
        ],
    })
        .populate("users", "-password")
        .strictPopulate("latestMessage");

    isChat = await User.populate(isChat, {
        path: "'latestMessage.sender'",
        select: "name pic email",
    });

    if (isChat.length > 0) {
        res.send(isChat[0]);
    }
    else {
        var chatData = {
            chatName: "sender",
            isGroupChat: false,
            users: [req.user._id, userId],
        };

        try {
            const createdChat = await Chat.create(chatData);

            const FullChat = await Chat.findOne({ _id: createdChat._id }).populate("users", "-password");

            res.status(200).send(FullChat);
        } catch (error) {
            res.status(400);
            throw new Error(error.message);
        }
    }
});

module.exports = { accessChat, fetchChats, createGroupChat };

It show the chat in postman with post request using token

……………………………………………………

and it show the Error—

“message”: “Chat.find(…).populate(…).strictPopulate is not a function”,
“stack”: “TypeError: Chat.find(…).populate(…).strictPopulate is not a functionn at D:ProjectChatNETbackendcontrollerschatControllers.js:22:10n at asyncUtilWrap (D:ProjectChatNETnode_modulesexpress-async-handlerindex.js:3:20)n at Layer.handle [as handle_request] (D:ProjectChatNETnode_modulesexpresslibrouterlayer.js:95:5)n at next (D:ProjectChatNETnode_modulesexpresslibrouterroute.js:144:13)n at D:ProjectChatNETbackendmiddlewareauthMiddleware.js:18:13n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)”

How to write unit test cases for my code for the confirmation madal

import {createConfirmationModal } from ‘/form.js’;

I’m trying to write unit test cases for my code, but unable to write it

    this.store.on('auth:signout:submit', async () => {
      const { pathname } = this.store.location;
      const pagePath = `${this.store.hrefRoot}/my-account/orders`;
      if (pathname === pagePath ) {
        this.ordersWarningModal(pathname);
      } else {
        this.orders(pathname);
      }
    });

  async pagePathWarningModal(pathname) {
    const ph = await getPlaceholders();
    const onConfirm = async () => {
      this.onSignOutPage(pathname);
    };

    try {
      await createConfirmationModal({
        onConfirm,
        title: ph.Delete,
        confirmText: ph.leave,
        abortText: ph.cancel,
      });
    } catch (e) {
      log.error('failed to open a modal: ', e);
    }
  }

  async onSignOutPage(pathname) {
    localStorage.removeItem(Hello_var);
  }

Here the createConfirmationModal is the function, to create a modals.

How to write the unit test cases for this js code where i can test if the modal is opened in pagepath and check with proper titles

How can i bind “store” correctly?

I wrote the code using a youtube video tutorial. I also wrote the same code written in the video tutorial on my computer, but the result was not good. The problem is that I am using redux to add an api file. If I connect index.js and store as follows, it gives me an error.

Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
    at Function.entries (<anonymous>)
    at Object.injectEndpoints (http://localhost:3000/static/js/bundle.js:66563:36)
    at baseCreateApi (http://localhost:3000/static/js/bundle.js:66581:16)
    at ./src/reducer/emehmonApi.js (http://localhost:3000/static/js/bundle.js:7038:85)
    at options.factory (http://localhost:3000/static/js/bundle.js:189281:31)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:188687:33)
    at fn (http://localhost:3000/static/js/bundle.js:188938:21)
    at ./src/reducer/index.js (http://localhost:3000/static/js/bundle.js:7105:69)
    at options.factory (http://localhost:3000/static/js/bundle.js:189281:31)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:188687:33)
import React, { Suspense } from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter, HashRouter } from "react-router-dom";
import Spinner from "./views/Spinner/Spinner";
import "./style.scss";
import { Provider } from "react-redux";
import store from "./reducer";

ReactDOM.render(
  <BrowserRouter>
    <Suspense fallback={<Spinner />}>
      <HashRouter>
        <Provider store={store}>
          <App />
        </Provider>
      </HashRouter>
    </Suspense>
  </BrowserRouter>,
  document.getElementById("root")
);

Using React Context returns Cannot read properties of undefined (reading ‘_context’)

I am trying to pass a value that is selected on click via Context to another component, however, I am receiving Cannot read properties of undefined (reading ‘_context’) error. After reading more on this error it seems that it is usually due to an improper export, but mine seems fine. How can I resolve this error and pass the value? Here is my code:
main.jsx:

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import DifferentComponent from './DifferentComponent.jsx';
export const DropDownButtonContext = React.createContext();

const items = [
  {
    actionName: 'Undo',
    icon: 'undo',
  },
  {
    actionName: 'Redo',
    icon: 'redo',
    disabled: true,
  },
  {
    actionName: 'Cut',
    icon: 'cut',
  },
  {
    actionName: 'Copy',
    icon: 'copy',
  },
  {
    actionName: 'Paste',
    icon: 'paste',
  },
];

const App = () => {
  const [menuItem, setMenuItem] = React.useState('');

  return (
    <div>
      <DropDownButtonContext.Provider value={menuItem}>
        <DropDownButton
          textField="actionName"
          items={items}
          text="Edit"
          onItemClick={(e) => {
            setMenuItem(e.item.actionName);
            console.log(menuItem);
          }}
        />
        <DifferentComponent />
      </DropDownButtonContext.Provider>
    </div>
  );
};
ReactDOM.render(<App />, document.querySelector('my-app'));

DifferentComponent.jsx:

import * as React from 'react';
import { DropDownButtonContext } from './main';

const value = React.useContext(DropDownButtonContext);

const DifferentComponent = () => {
  return (
    <div>
      <h1> {value}</h1>
    </div>
  );
};

export default DifferentComponent;

is there a way to show latest date of a map on maps using google maps api?

`I want to show the date of imagery of the particular address using google maps API? is there any date method or property for getting date from this google maps API?

function initMap(address1) { showAjaxLoader();
var geocoder = new google.maps.Geocoder();
var address = address1;
var latitude;
var longitude;
if (address != "") {
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            moveToGoogleMaps(latitude, longitude, address);
            GetFindImageInfo(latitude, longitude);
            GetPropertyInfo(latitude, longitude);
            //GetDamage(latitude, longitude);
        }
    });
}
hideAjaxLoader();
}

   function moveToGoogleMaps(latitude, longitude, address) { 

setTimeout(() => { const latlongs = { lat: latitude, lng: longitude };
 
const map = new google.maps.Map(document.getElementById("map"), { zoom: 20, center: latlongs, mapTypeId: 'satellite' }); 
 
const marker = new google.maps.Marker({ position: latlongs, map: map, date: });

 // Add event listener for marker hover
    marker.addListener('mouseover', () => {
        // Create info window with marker details
        const infoWindow = new google.maps.InfoWindow({
            
            content: `Location: ${address+marker.date}`
        });
        // Open info window
        infoWindow.open(map, marker);`your text`
    });

}, 1000);
}

here is the code that i am trying for getting date for particular address.

following is the script that iam using

<script src=”https://maps.googleapis.com/maps/api/js?key=Your-key&callback=initMap&libraries=places&v=weekly” defer></script>

`

How to Add a diffrent FONT in this script? [duplicate]

Hello all i have this script running how do i add a font in this? I Not that good at this but i,m learning . I tryed some thinks so i need some help at this.

<!DOCTYPE html>
<html>
<style>

body {
  background-image: url('****/*****/Weerbericht_Achterhoek.jpg');
  background-repeat: no-repeat;  
  background-attachment: fixed;
  background-size:  100% 100%;
</style>
<body>


<iframe id="myFrame" frameborder="0" scrolling="no" style="height:800px;width:8000px;border:none;" src='https://****/****/loadknmi.php'></iframe>
<script>
var frame = document.getElementById('myFrame');
frame.onload = function () {
var body = frame.contentWindow.document.querySelector('body');
body.style.color = 'white';
body.style.fontSize = '23px';
body.style.lineHeight = '20px';



};
</script>



</body>
</html>

How to view kml files in custom google maps the same as it appears in google earth

I have a simple kml file that have MultiGeometry tag with both LineString and Point within:

here is how the kml file looks :

<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
    <name>lines.kmz</name>
    <Style id="LineStyle00">
        <LabelStyle>
            <color>ff0000ff</color>
            <scale>2.0</scale>
        </LabelStyle>
        <LineStyle>
            <color>ff00ff55</color>
            <width>3</width>
        </LineStyle>
        <PolyStyle>
            <color>00000000</color>
            <outline>0</outline>
        </PolyStyle>
    </Style>
    <Folder id="FeatureLayer0">
        <name>مسارات المصارف الجديدة</name>
        <Snippet maxLines="0"/>
        <Placemark id="ID_00000">
            <name>العياط</name>
            <Snippet maxLines="0"/>
            <description>&lt;html xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:msxsl="urn:schemas-microsoft-com:xslt"&gt;

&lt;head&gt;

&lt;META http-equiv="Content-Type" content="text/html"&gt;

&lt;meta http-equiv="content-type" content="text/html; charset=UTF-8"&gt;

&lt;/head&gt;

&lt;body style="margin:0px 0px 0px 0px;overflow:auto;background:#FFFFFF;"&gt;

&lt;table style="font-family:Arial,Verdana,Times;font-size:12px;text-align:left;width:100%;border-collapse:collapse;padding:3px 3px 3px 3px"&gt;

&lt;tr style="text-align:center;font-weight:bold;background:#9CBCE2"&gt;

&lt;td&gt;العياط&lt;/td&gt;

&lt;/tr&gt;

&lt;tr&gt;

&lt;td&gt;

&lt;table style="font-family:Arial,Verdana,Times;font-size:12px;text-align:left;width:100%;border-spacing:0px; padding:3px 3px 3px 3px"&gt;

&lt;tr&gt;

&lt;td&gt;SHAPE&lt;/td&gt;

&lt;td&gt;Polyline&lt;/td&gt;

&lt;/tr&gt;

&lt;tr bgcolor="#D4E4F3"&gt;

&lt;td&gt;الاسم&lt;/td&gt;

&lt;td&gt;العياط&lt;/td&gt;

&lt;/tr&gt;

&lt;tr&gt;

&lt;td&gt;SHAPE_Length&lt;/td&gt;

&lt;td&gt;3299.179106&lt;/td&gt;

&lt;/tr&gt;

&lt;/table&gt;

&lt;/td&gt;

&lt;/tr&gt;

&lt;/table&gt;

&lt;/body&gt;

&lt;/html&gt;</description>
            <styleUrl>#LineStyle00</styleUrl>
            <MultiGeometry>
                <LineString>
                    <coordinates>
                        31.22167327537224,29.60699409142521,0 31.21864638138206,29.60718181167419,0 31.21700996113995,29.60744215099063,0 31.21414622689401,29.60878103953701,0 31.21295610437081,29.60959924916077,0 31.20477400640138,29.60788844697299,0 31.20298882177771,29.61257455770906,0 31.19333333292129,29.60888888869802,0 
                    </coordinates>
                </LineString>
            <Point><coordinates>31.21295610437081,29.60959924916077,0</coordinates></Point></MultiGeometry>
        </Placemark>

    </Folder>
</Document>
</kml>

when I open this file on google earth it works like charm with both elements shown perfectly, but when I open it on my Google Maps using js script as follows:

            var kml_layer = new google.maps.KmlLayer(src, {
                suppressInfoWindows: true,
                preserveViewport: true,
                map: map
            });

it only shows LineString without the point shown on it .. any idea what could be causing this?

Trying to nest Text components with different font properties inside another Text component. In one case, the line height cuts some of the text

I have a React Native application and I am trying to create a sentence where the different words have different styles, so I created a Text component and tried nesting other Text components with different styles inside of it. For example this works fine:

        <Text>
            <HeaderText2>Hello</HeaderText2>
            <HeaderText6>From</HeaderText6>
            <HeaderText2>The Other Side</HeaderText2>
        </Text>

And the result is:

enter image description here

However, if I swap the components so that the component with smaller line-height and font-size is first, it breaks somehow and nothing gets rendered.

        <Text>
            <HeaderText6>Hello</HeaderText6>
            <HeaderText2>From</HeaderText2>
            <HeaderText6>The Other Side</HeaderText6>
        </Text>

And this is how my HeaderText2 and HeaderText6 styled components look like:

const HeaderText2 = styled.Text`
    font-size: 30px;
    line-height: 39px;
`;

const HeaderText6 = styled.Text`
    font-size: 12px;
    line-height: 16px;
`;

Anyone have any clue why this might be happening? It’s important to remember that this is React Native, so there might be some React Native shenanigans happening. When I delete the line-height of both components, it works fine but I want the line-height of the component with bigger line-height to take precedence and not be without line-height.

Distinct value in object of array and remaining values into another array

This is the array of javascript objects. I want these javascript objects will merge into a single javascript object according to their same property value and remaining values come into another array of named info.

This is the original array:

const array = [
    {
        price: 27,
        colors: "BLACK",
        size: "S"
    },
    {
        price: 23,
        colors: "GREEN",
        size: "S"
    },
    {
        price: 0,
        colors: "GREEN",
        size: "M"
    },
    {
        price: 0,
        colors: "OLIVE",
        size: "S"
    },
    {
        price: 65,
        colors: "RED",
        size: "S"
    },
    {
        price: 12,
        colors: "RED",
        size: "M"
    },
    {
        price: 12,
        colors: "BLACK",
        size: "L"
    },
    {
        price: 34,
        colors: "RED",
        size: "L"
    },
    {
        price: 43,
        colors: "OLIVE",
        size: "M"
    },
    {
        price: 23,
        colors: "OLIVE",
        size: "L"
    },
    {
        price: 34,
        colors: "GREEN",
        size: "L"
    },

]

This is the required array:

 [
    {
        colors: "BLACK",
        info: [{size: "S", price: 27}, {size: "L", price: 12}]
    },
    {
        colors: "GREEN",
        info: [{size: "S", price: 23}, {size: "M", price: 0}, {size: "L", price: 23}]
    },
    {
        colors: "RED",
        info: [{size: "S", price: 65}, {size: "M", price: 12}, {size: "L", price: 34}]
    },
    {
        colors: "OLIVE",
        info: [{size: "S", price: 0}, {size: "M", price: 43}, {size: "L", price: 23}]
    },
]

Kindly provide me with some solutions. Thanks

Ionic Capacitor (Angular): how to prevent closing of keyboard after “submit” with enter key

In Ionic Capacitor (I am using Angular): How do I keep displaying the keyboard open, prevent it from closing, when the user submits the form or input?

I know there are questions like this one on StackOverflow, but they refer to Ionic Cordova and not Ionic Capacitor.

I want this to work on native IOS/Android, I don’t care about PWA. (and dont care about Desktop-Web of course, since it doesnt even have a keyboard on the screen).

Blazor Java script interop

I have this javascript library that is written in TypeScript

(function(f) {
    if (typeof exports === "object" && typeof module !== "undefined") {
        module.exports = f()
    } else if (typeof define === "function" && define.amd) {
        define([], f)
    } else {
        var g;
        if (typeof window !== "undefined") {
            g = window
        } else if (typeof global !== "undefined") {
            g = global
        } else if (typeof self !== "undefined") {
            g = self
        } else {
            g = this
        }
        g.richTextEditor = f()
    }
}
)(function() {
    var define, module, exports;
    return (function() {
        function r(e, n, t) {
            function o(i, f) {
                if (!n[i]) {
                    if (!e[i]) {
                        var c = "function" == typeof require && require;
                        if (!f && c)
                            return c(i, !0);
                        if (u)
                            return u(i, !0);
                        var a = new Error("Cannot find module '" + i + "'");
                        throw a.code = "MODULE_NOT_FOUND",
                        a
                    }
                    var p = n[i] = {
                        exports: {}
                    };
                    e[i][0].call(p.exports, function(r) {
                        var n = e[i][1][r];
                        return o(n || r)
                    }, p, p.exports, r, e, n, t)
                }
                return n[i].exports
            }
            for (var u = "function" == typeof require && require, i = 0; i < t.length; i++)
                o(t[i]);
            return o
        }
        return r
    }
    )()({
        1: [function(require, module, exports) {
            "use strict";
            Object.defineProperty(exports, "__esModule", {
                value: true
            });
            exports.showHello = void 0;
            const greet_1 = require("./greet");
            function showHello(divName, name) {
                const elt = document.getElementById(divName);
                elt.innerText = (0,
                greet_1.sayHello)(name);
            }
            exports.showHello = showHello;

        }
        , {
            "./greet": 2
        }],
        2: [function(require, module, exports) {
            "use strict";
            Object.defineProperty(exports, "__esModule", {
                value: true
            });
            exports.sayHello = void 0;
            function sayHello(compiler) {
                return `Hello from ${compiler}`;
            }
            exports.sayHello = sayHello;

        }
        , {}]
    }, {}, [1])(1)
});

and I am trying to execute showHello function in this library using JSInterop in Blazor using following code

public class TypeScriptInterop
{
    private readonly Lazy<Task<IJSObjectReference>> _moduleTask;

    public TypeScriptInterop(IJSRuntime jsRuntime)
    {
        _moduleTask = new(()=>
        jsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/Blazored.RichTextEditor/js/bundle.generated.js").AsTask());
    }

    public async ValueTask TsButtonClicked()
    {
        var javaScript = await _moduleTask.Value;
        if (_moduleTask.IsValueCreated)
        {
            Console.WriteLine("Captured Js");
        }
        await javaScript.InvokeVoidAsync("richTextEditor.showHello", "greeting", "Ubhaya");
    }
}

when I run this I get the error message saying

WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find ‘richTextEditor.showHello’ (‘richTextEditor’ was undefined).

but if I use <script src="./_content/Blazored.RichTextEditor/js/bundle.generated.js"></script> inside the index.html in blazor wasm project. it works correctly.

I am trying to create a Blazor component library. is there a way to do this in my current approach since I want to use JS isolation.

How to preserve GPT-3/4 base knowledge when adding indexed data?

I’m conducting experiments with LangchainJS, Pinecone, and OpenAI.

My goal is to use the model (for now GPT-3, as I still don’t have GPT-4 API access) to assist me in my coding job by adding new data on specific frameworks.

I have already indexed the craft.js documentation and codebase, and by using both ConversationalRetrievalQAChain or Agent by creating a tool for this specific index, the model is quite capable of answering my questions.

The issue I’m facing is that I feel it loses its base capacities. For example, it is never able to generate code based on that information, or worse, if I ask it to generate code on another framework (e.g., Next.js), it either tells me it doesn’t know or gives me a nonsensical response like “Even though we can create Next.js components using Craft.js, it is not the best tool to achieve this task.”

But if I try this prompt:

Generate a Next.js component that allows file uploads.

in the playground or with model.call(prompt), it generate a nearly perfect code.

It seems that when I add embeddings to the model, it becomes overly focused on this new data and loses some of its power.

Is there a way to maintain the power of the base model and add new knowledge to it? If so, what is the best approach to achieve this?

Want to open a quick create form after creating a new account in Microsoft Dynamics 365 Sales

I want to open a Quick Create Task form with the regarding field prepopulated with the newly created account’s name. When a new account is being created in dynamics 365 sales it open a quick create for for the task but it is not being prepopulated with the account name that i just created. the account name should be prepopulated in the regarding field which is a lookup field to the accounts on the task form.

function taskFormAccount() {
    var formType = Xrm.Page.ui.getFormType();
    if (formType === 1) {
        Xrm.Navigation.openForm({
            entityName: "task",
            useQuickCreateForm: true
        });
    }
}

Update this code so that when account is created it should open quick create form of task prepopultaed with account lookup in the regarding field in Task form in dynamcs 365 sales