How to open an Electron child window after clicking an html button?

I am trying to have an electron app with three clickable html buttons. No problem there, but I can’t figure out how to make the buttons open a child window for electron. I can get it to open all of the windows when the process starts, but never when a button is clicked.

I’ve had several errors where it says the function isn’t defined, when it is imported and defined properly. Chances are I’ve messed it up more when trying to troubleshoot. I’ve tried multiple solutions posted on here, but none of them have worked. I am experienced in js, but completely new to Electron, so this is all crazy to me.

The current code can be found at: https://github.com/SoullessCookie/Uppitty

Server is sending a request to Open Api Vision API with right credentials but getting invalid error

I have a server that I have recently created to interact with OpenAI’s vision api. I went on their documentation and implimented the code for the server correctly. I am running into an issue every single time I submit a request to the api. I have Chat GPT plus that I pay for ever single month which should give me access to the api. I am not sure why it is telling me that the model is invalid or I do not have permission. Can someone help me.

Here is my server:

const express = require('express');
const OpenAIApi = require("openai");
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;
console.log(process.env.OPENAI_API_KEY)
const openai = new OpenAIApi({
  apiKey: process.env.OPENAI_API_KEY,
});

app.use(express.json());

app.post('/api/v1/analyze-image', async (req, res) => {
    const imageUrl = req.body.imageUrl;

    if (!imageUrl) {
        return res.status(400).send({ error: 'No image URL provided' });
    }

    try {
      const response = await openai.chat.completions.create({
        model: "gpt-4-vision-preview",
        messages: [
          {
            role: "user",
            content: [
              { type: "text", text: "What’s in this image?" },
              {
                type: "image_url",
                image_url: {
                  "url": imageUrl,
                },
              },
            ],
          },
        ],
      });

       res.json(response.data.choices[0]);
    } catch (error) {
        res.status(500).send({ error: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

here is what I am getting back as a response:

{
    "error": "404 The model `gpt-4-vision-preview` does not exist or you do not have access to it. Learn more: https://help.openai.com/en/articles/7102672-how-can-i-access-gpt-4."
}

Here is what the documentation says:

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const response = await openai.chat.completions.create({
    model: "gpt-4-vision-preview",
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "What’s in this image?" },
          {
            type: "image_url",
            image_url: {
              "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
            },
          },
        ],
      },
    ],
  });
  console.log(response.choices[0]);
}
main();

Not sure why it is saying I do not have access or the model is wrong. Is there anything else that can be causing this issue.

Migrating from CRA to Vite: Unable to determine current node version

Migrating from CRA to Vite for a react project. Vite builds ok but displays a blank page after build. There’s a console error:

@emotion_styled_macro.js:32600 Uncaught TypeError: Unable to determine current node version
    at versionIncluded (@emotion_styled_macro.js:32600:15)
    at isCore (@emotion_styled_macro.js:32614:33)
    at node_modules/resolve/lib/core.js (@emotion_styled_macro.js:33117:22)
    at __require2 (chunk-XZ6WXOVE.js?v=dcdf163e:2132:50)
    at node_modules/resolve/index.js (@emotion_styled_macro.js:33350:18)
    at __require2 (chunk-XZ6WXOVE.js?v=dcdf163e:2132:50)
    at node_modules/babel-plugin-macros/dist/index.js (@emotion_styled_macro.js:43001:21)
    at __require2 (chunk-XZ6WXOVE.js?v=dcdf163e:2132:50)
    at node_modules/@emotion/babel-plugin/dist/emotion-babel-plugin.esm.js (@emotion_styled_macro.js:43851:42)
    at __init (chunk-XZ6WXOVE.js?v=dcdf163e:2129:56)

The project runs fine with CRA. I only use emotion as a dependency of Chakra UI, and I’m not keen on swapping out Chakra just because of this issue. Searched online and haven’t found anyone with the same issue or at least with a solution.

Thought that maybe it was a difference between how ESBuild and Babel handled the transform process so tried to duplicate CRA’s babel setup but no luck.

Here’s my Vite config:

export default defineConfig({
  build: {
    target: browserslistToEsbuild(),
  },
  plugins: [react({
    jsxImportSource: '@emotion/react',
    babel: {
    plugins: ['@emotion/babel-plugin'],
    },
    }),nodePolyfills({
    protocolImports: true,
    overrides: {
      // Since `fs` is not supported in browsers, we can use the `memfs` package to polyfill it.
      fs: 'memfs',
    }
  }),
  legacy({
    targets: ['defaults', 'not IE 11'],
  }),
  babel({
    babelConfig:{
      presets:['@babel/preset-react']
    }
  }),
  ],
})

oracledb nodejs package getConnection(‘hr’) method hang after few hours

I have created the express server application which connect to oracle database in order to perform DB operations. That application works fine in dev environment and then I published it in ubuntu vm using pm2. Initially it works fine but after few hours getConnection(‘hr’) method hang the request.

Inside application, First I create the oracledb connection pool at the startup of the express app.
Here is the code for connection pool.

const initialize = async () => {
    const pool = await oracledb.createPool({
        user: 'username',
        password: 'password',
        connectString: 'x.x.x.x:1521/sampledev',
        poolMin: 5,
        poolMax: 10,
        poolIncrement: 1,
        poolAlias: "hr",
    });

    console.log("Connected to the oracle db pool");
}

Here is the endpoint that use oracle connection.

app.get('/dbstatus', async (req, res) => {
    try {
        oracleConnApps = await oracledb.getConnection('hr');
        console.log("DB Connected")

        // do stuff

        res.status(200).send({ status: true, data: "OK" });
    } catch (err) {
        console.log("CATCH EXECUTE")
        console.log({ status: true, data: err.message })
        res.status(400).send({ status: false, data: err.message });
    } finally {
        console.log("FINALLY EXECUTE")
        if (oracleConnApps) await oracleConnApps.close();
    }
})

After few hours getConnection method hang the server and it does not trigger the catch block.

Bunx Prisma Undefined

i just install Prisma using Bun runtime
it work, but then when i check the version for the second time it say Error : undefined
i can’t generate, but at first (When i try to reinstalling it can do init stuff)
now i give up it’s always say Error : undefined

why i can’t use Prisma in Bun Runtime?

Folder basic structure

When i check Version

error: script not found “/home/harriaz007/example/data/node_modules/prisma/build/child”

How should I store data in Firestore for a logging app?

I am working on a web app using React and Firebase Firestore. The app lets users log skills they learn each day and how long they learn. The current structure for my database is just a single collection where the documents are individual logs. A document looks like this:

// document in collection 'logs'
createdAt: timestamp
hours: number
minutes: number
notes: string
skill: string
uid: string

The logs are displayed as a table, so when the user loads into the dashboard I run this query to get their logs:

const logsRefQuery = query(
    collection(db, 'logs'),
    where('uid', '==', user?.uid || null),
    orderBy('createdAt', 'desc')
)

The things I would like to be able to do with the database data are:

  1. Being able to sort the table by different fields (Skill, date created, time spent). If I want to do this right now it seems like I need a composite query for every combination of user id and the field to sort by.

  2. Getting the total hours logged for each skill of the user

  3. Getting the total hours of all skills logged on a certain day.

Is this possible with the current way I have the database set up?

Will BunJS ever get used by big companies – will its extensive use of the JavaScriptCore engine impact its use in the future?

I have been checking out BunJS over the past few weeks, and used it as a package manager extensively. I have not used it as a runtime yet, but I did do some research about its JS-rendering engine, JavaScriptCore. It seems that it is primarily used in Apple operating systems. From what I have read, it is also more scalable than its rivals, NodeJS and DenoJS, and can handle many more requests per second. Additively, I also read that it is compatible with NodeJS libraries. But, although compatible with NodeJS libraries, will its use of the JavaScriptCore engine make it harder for big companies that already use NodeJS like Uber to implement it in their backend and server-side systems, or will this result in the mere opposite?

I have seen other StackOverflow questions stating errors based on their operating system like this one.

I have also tried to use Bun on my older computers, and somehow it will not install packages with bun i PACKAGE_NAME or bun install PACKAGE_NAME, somehow related to my operating system drivers.

Does anybody know if this will impact its use in the future, or will it just get more mature over time?

Webpack Error with –entry How do I fix this? Imports are not working

So I typed this into my terminal node_modules/.bin/webpack –entry ./src/index.js -o dist and it returns this error

node_modules.binwebpack.ps1 cannot be loaded because running scripts is
disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

  • node_modules/.bin/webpack –entry ./src/index.js -o dist
  •   + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    
    

I expected to use webpack and this commannd would allow me to import everything for it but it did not work.

catching error in GET request is retrieving Uncaught Error: Rendered fewer hooks than expected

I am having some difficulties with checking the side scenario of an API request.
I have this component:

import * as React from "react";
import {
    getOrganizationByObjectId,
    updateOrganization
} from "../../../services/apiRequests";
import {useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import {formStructure, yupValidation, defaultValue} from "../../../schemas/OrganizationSchemas.jsx";
import {UPDATE} from "../../../utils/definitions.jsx";
import FormEntity from "../../../components/FormEntity.jsx";
import Message from "../../../components/Message.jsx";
import {BeatLoader} from "react-spinners";

const EditOrganization = () => {
    const [values, setValues] = useState(defaultValue());
    //const [loading, setLoading] = useState(true);
    const [errorMsg, setErrorMsg] = useState("");
    const {objectId} = useParams();

    useEffect(() => {
        getOrganizationByObjectId(objectId)
            .then((response) => setValues(response))
            .catch((error) => {
                setErrorMsg(error.error);
            });
    }, [objectId]);

    const renderFormEntity = () => {
        if (errorMsg === "") {
            return (
                <FormEntity
                    formStructure={formStructure()}
                    yupValidation={yupValidation()}
                    submitMethod={updateOrganization}
                    title={"Edit Organization"}
                    values={values}
                    formType={UPDATE}
                    forwardToAfterRequest={'/organizations/list'}
                />
            );
        }
        return null;
    };

    return (
        <>
            <Message message={errorMsg} severity={"error"}/>
            {renderFormEntity()}
        </>
    );
};

export default EditOrganization;

On the first run, it should fetch the data from the server using the useEffect() hook.
while giving proper and valid ID, and no error has been caught by the hook everything works perfectly.

But when I deliver some wrong ID the server receives an exception, and the expectation from the code is to store it inside the state errorMsg.

  • I have checked and error. the error.error has the correct value.

for some reason, I am getting this error:

Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

I have debugged the code, and the error is related to the state errorMsg when removing that setErrorMsg() the code is working perfectly but without the error message..

if the errorMsg is not empty I am generating the Message component:

const Message = ({message, severity}) => {
    return (
        message !== '' &&
        <Alert severity={severity} sx={{mt: 3, mb: 3, width: "100%"}}>
            <div style={{ marginRight: '20px' }}>{message}</div>
        </Alert>
    );
}

What am I missing here?

Why is my console.log showing an empty array inside my function, but before and after the function showing the correct value?

Can anyone explain why my console.log(‘in function’, randomMeals) is returning an empty array but the console.logs before and after the function have the correct value? I’m trying to do a drag and drop from one array to the other. Currently the only way to fix the problem is to comment in OR out anything, basically alter the page so that the page rerenders and then I’m able to successfully drag and drop from randomMeals to dropCalendar.

Primary component I’m having the issue in:

import React, { useState } from 'react';
import './HomepageCalender.css';
import { Meal } from '../../types';
import RecipeCard from '../RecipeCard/RecipeCard';
import { useDrop } from 'react-dnd';

interface HomepageCalenderProps {
  randomMeals: Meal[];
  toggleLock: (idMeal: string) => void;
}

interface DroppedMeal {
  id: string;
}

const HomepageCalender: React.FC<HomepageCalenderProps> = ({ randomMeals, toggleLock }) => {
  const [dropCalendar, setDropCalendar] = useState<Meal[]>([]);

  const [{ isOver }, drop] = useDrop(() => ({
    accept: 'recipe-card',
    drop: (droppedMeal: DroppedMeal) => {
      console.log('meal', droppedMeal);
      addRecipeCardToBoard(droppedMeal.id);
      // console.log('hook', randomMeals)
    },
    collect: (monitor) => ({
      isOver: !!monitor.isOver(),
    }),
  }));
  
  console.log('before funtion', randomMeals)
  const addRecipeCardToBoard = (id: string) => {
    console.log('in function', randomMeals)

    const filteredRandomMeals = randomMeals.filter((meal) => meal.idMeal === id);

    const uniqueDroppedMeals = filteredRandomMeals.filter(
      (meal, index, self) =>
      index === self.findIndex((m) => m.idMeal === meal.idMeal)
      );
    
      setDropCalendar((prevDropCalendar) => [...prevDropCalendar, ...uniqueDroppedMeals]);
  };
  console.log('after function', randomMeals)

  return (
    <div className='homepage-calendar-container'>
      <h4 className='date'>Date</h4>
      <div className='droppable-area' ref={drop}>
        {dropCalendar.map((meal) => (
          <RecipeCard
            key={meal.idMeal}
            idMeal={meal.idMeal}
            strMeal={meal.strMeal}
            strMealThumb={meal.strMealThumb}
            toggleLock={toggleLock}
            locked={true}
          />
        ))}
      </div>
    </div>
  );
};

export default HomepageCalender;

Parent component for reference:

import React, { useEffect, useState } from 'react';
import Header from '../Header/Header';
import WelcomeBox from '../WelcomeBox/WelcomeBox';
import Footer from '../Footer/Footer';
import RandomMealForm from '../RandomMealForm/RandomMealForm';
import HomepageCalender from '../HomepageCalender/HomepageCalender';
import { fetchSingleRandomRecipe } from '../../apiCalls';
import { RandomMealProps } from '../../types';

const Homepage: React.FC = () => {
  const [numberOfMeals, setNumberOfMeals] = useState<number>(5);
  const [randomMeals, setRandomMeals] = useState<RandomMealProps[]>([]);

  const toggleLock = (idMeal: string) => {
    const updatedRandomMeals = randomMeals.map((meal) => {
      if (meal.idMeal === idMeal) {
        return { ...meal, locked: !meal.locked }; // Create a new object
      }
      return meal;
    });

    setRandomMeals(updatedRandomMeals);
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const fetchedMeals = [];
        for (let i = 0; i < numberOfMeals; i++) {
          const data = await fetchSingleRandomRecipe();
          if (data?.meals) {
            const newMeals = data.meals.map((meal: RandomMealProps) => ({
              ...meal,
              locked: false,
            }));
            fetchedMeals.push(...newMeals);
          }
        }

        const uniqueMeals = fetchedMeals.filter(
          (meal, index, self) =>
            index === self.findIndex((m) => m.idMeal === meal.idMeal)
        );

        setRandomMeals(uniqueMeals);
      } catch (error) {
        console.error(error);
        // Handle errors here if needed
      }
    };

    fetchData();
  }, [numberOfMeals]);

  useEffect(() => {
    console.log('homepage', randomMeals);
  }, [randomMeals]);

  return (
    <div className='homepage'>
      <Header />
      {randomMeals.length > 0 && (
        <WelcomeBox randomMeals={randomMeals} toggleLock={toggleLock} />
      )}
      <RandomMealForm
        numberOfMeals={numberOfMeals}
        setNumberOfMeals={setNumberOfMeals}
        setRandomMeals={setRandomMeals}
        randomMeals={randomMeals}
        toggleLock={toggleLock}
      />
      <HomepageCalender randomMeals={randomMeals} toggleLock={toggleLock} />
      <Footer />
    </div>
  );
};

export default Homepage;

I tried putting a useCallback around the function, putting a useCallback and useMemo in the parent component so that the data would persist but no luck. And I already have a useEffect in the parent component to make the randomMeals array persist. The array is available everywhere else in the primary component, just not in the addRecipeCardToBoard function. Any suggestions would be helpful TY!

sync event not firing when user goes online

I’m trying to sync offline data with the server after a user comes back online. I’m trying to follow these steps that I have found doing research on this. This information I’m using as a guide. BTW, I’m new to this, so I’m still trying to figure out the logic flow of everything.

To sync IndexedDB to a server in the background using service workers,
you can use the background sync feature of service workers. This
feature allows you to defer actions until the user has stable
connectivity. Here are the steps to follow:

Register a service worker in your application’s JavaScript file using
feature detection. You can use the following code snippet: JavaScript
AI-generated code. Review and use carefully. More info on FAQ.
I have this function in my app.js file and it is called at the bottom of every page for offline capabilities

if (navigator.serviceWorker) {
    navigator.serviceWorker.register('serviceworker.js');
} 

In your
service worker, add an event listener for the sync event. This event
is triggered when the user has stable connectivity. You can use the
following code snippet: JavaScript AI-generated code. Review and use
carefully. More info on FAQ.
I have this function in my sw.js file

self.addEventListener('sync', function(event) {
    if (event.tag === 'sync_date_time') {
        console.log('sync event has been fired');
        // event.waitUntil(syncData());
    }
});

In the syncData function, retrieve the data from IndexedDB and send it to the server using the
fetch API. You can use the following code snippet: JavaScript
AI-generated code. Review and use carefully. More info on FAQ.
This is the easy part, just sending the information to the server that I get pulled from IndexedDB. Although my function will be a little different

function syncData() {
    return getIndexedDBData().then(function(data) {
        return fetch('/sync', {
            method: 'POST'
            body: JSON.stringify(data),
            headers: {'Content-Type': 'application/json'}
        });
    });
}

In your application’s frontend code, request a sync by calling the register() method on the SyncManager interface. You can
use the following code snippet: JavaScript AI-generated code. Review
and use carefully. More info on FAQ.
This function I have in my dateTimeJS.js file.

async function requestBackgroundSync() {
    const registration = await navigator.serviceWorker.ready;
    await registration.sync.register(BACKGROUND_QUERY_DATE_TIME);
}

Finally, handle the sync
event in your server-side code and update the server-side database
with the data sent from the client.

I have my sw registered, I have the function requestBackgroundSync in the js file that is loaded with page that has the form. Here is my dateTime.js file:

const BACKGROUND_QUERY_DATE_TIME = 'sync_date_time';

const IDB = function init() {
    let db = null;
    let DBOpenReq = indexedDB.open('dateTimeDB',1);

    DBOpenReq.addEventListener('success', evt => {
        db = evt.target.result;
    });

    DBOpenReq.addEventListener('upgradeneeded', evt => {
        db = evt.target.result;
        const objectStore = db.createObjectStore('date_time',{
            autoIncrement: true
        })
    })

    let form = document.getElementById('date_time_form');
    
    form.addEventListener('submit', async evt => {
        evt.preventDefault();
        
        let fm = document.getElementById('form_msg');
        fm.innerHTML = '';
    
        const data = new FormData(form);
        const formData = Object.fromEntries(data.entries());
    
        let userData = {
            uID: formData.uID,
            tz: formData.time_zone,
            tf: formData.time_format,
            df: formData.date_format
        }

        try{
            const req = await fetch('../date-time-format/src/inc/dateTimeAPI.php',{
                method: 'POST',
                headers: {'Content-Type':'application/json'},
                body: JSON.stringify(userData)
            });
            
            const res = await req.json();
            
            if(res.status === 'ok'){
                fm.classList.remove('w3-text-red');
                fm.classList.add('w3-text-green');
                fm.innerHTML = res.msg;
            }
            else if(res.status === 'error'){
                fm.classList.remove('w3-text-green');
                fm.classList.add('w3-text-red');
                fm.innerHTML = res.msg;
            }
        }
        catch{
            // Clear any data previously saved in the store
            clearStore(db,'date_time');

            let tx = db.transaction('date_time','readwrite');
            let store = tx.objectStore('date_time');
            let req = store.add(userData);

            req.onsuccess = evt => {
                fm.classList.remove('w3-text-red');
                fm.classList.add('w3-text-green');
                fm.innerHTML = 'Date/Time Options have been set.';
            }
        }
    
    })
}

async function requestBackgroundSync() {
    const registration = await navigator.serviceWorker.ready;
    await registration.sync.register(BACKGROUND_QUERY_DATE_TIME);
}
IDB();
requestBackgroundSync();

When I go to the page with the form, I use the devTools to go into offline mode. This puts the form data into the IndexedDB after the form submission. This works as expected. Then I click on the checkbox to make the page be “online” but nothing happens. I would expect that the console.log would fire to let me know that there was a sync event.

I’m sure there is something simple that I am missing but I have not yet run across a solution to my problem.

Question
What am I missing to have the sync event fire when I bring the browser back online?

I have found these questions. The first link had no answers. The second question was of no help either. Then I found the third link here and I tried to follow how they implemented the sync, but it is still not firing.

When and how are sync events fired in service workers?
Background sync not firing event in serviceworker
Call Back not fired when listening to ‘sync’ event in service worker

If ya’ll need more information/code, please let me know.

Preview for uploaded Json file content

I need to display the Json contents to the textbox from uploaded Json file.

my HTML code,

<input type="file" value="Import" name="myFiles" onchange="metadataFile()"/><br />
<textarea id="result">  
</textarea>

my JavaScript Code,

window.metadataFile = function() {
var files = document.getElementsByName(‘myFiles’).files;
console.log(files);
if (files.length <= 0) {
return false;
}
var fr = new FileReader();
fr.onload = function(e) {
console.log(e);
var result = JSON.parse(e.target.result);
var formatted = JSON.stringify(result, null, 2);
document.getElementById(‘result’).value = formatted;
}
fr.readAsText(files.item(0));
}

jsfiddle link : https://jsfiddle.net/magendiran/zbjpL6rf/

Kindly help on this.

The onPress button in my native app isnt working for some reason

import { useState } from "react";
import {
  View,
  ScrollView,
  SafeAreaView,
  Text,
  TouchableOpacity,
  StyleSheet,
  Modal,
} from "react-native";
import { Stack, useRouter } from "expo-router";
import { COLORS, icons, images, SIZES } from "../constants";
import {
  Nearbyjobs,
  Popularjobs,
  ScreenHeaderBtn,
  Welcome,
} from "../components";

const Home = () => {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [openNav, setOpenNav] = useState(false);

  const toggleNavigation = () => {
    setOpenNav(false);
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: COLORS.lightWhite }}>
      <Stack.Screen
        options={{
          headerStyle: {
            backgroundColor: COLORS.lightWhite,
          },
          headerShadowVisible: false,
          headerLeft: () => (
            <TouchableOpacity onPress={toggleNavigation}>
              <ScreenHeaderBtn iconUrl={icons.menu} dimension="60%" />
            </TouchableOpacity>
          ),
          headerRight: () => (
            <ScreenHeaderBtn iconUrl={images.profile} dimension="100%" />
          ),
          headerTitle: "Jobbed",
        }}
      />

      <ScrollView showsVerticalScrollIndicator={false}>
        {openNav ? (
          <Text>Nav is working</Text>
        ) : (
          <Text>Not working error !!!!!</Text>
        )}
        <View style={{ flex: 1, padding: SIZES.medium }}>
          <Welcome
            searchTerm={searchTerm}
            setSearchTerm={setSearchTerm}
            handleClick={() => {
              if (searchTerm) {
                router.push(`/search/${searchTerm}`);
              }
            }}
          />
          <Popularjobs />
          <Nearbyjobs />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  modalContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0, 0, 0, 0.5)", // semi-transparent background
  },
  menu: {
    backgroundColor: COLORS.lightWhite,
    padding: SIZES.medium,
    borderRadius: 10,
  },
});

export default Home;

i want to have a navbar component but im testing it with just an ordinary view for now, the onPress doesnt trigger the use state and i dont know why. See how im testing it.

   {openNav ? (
          <Text>Nav is working</Text>
        ) : (
          <Text>Not working error !!!!!</Text>
        )}

The general code is working cos it shows the option of when the state is false, the problem now is the onpress isnt trigeering the function to change the state

Javascript – append object to an existing key within an existing object

Within my app, I have an object with the following structure

object = {"chatid1": {"messageId1": {message: "hello", id: 293839}, "messageId2": {message: "test", id: 2929292}}, "chatid2": {"messageId1": {message: 'hello', id: 292}}

I want to append a new message object (with its own key, e.g "messageId3") to a particular chatId. The result operation should mean that in the example above, "chatid1", should now look like the following:

"chatid1": {"messageId1": {message: "hello", id: 293839}, "messageId2": {message: "test", id: 2929292}, "messageId3": {message: "newMessage", id: 292121356}}

I tried to add the following code, however instead of appending an object, it replaced the value of whatever object[chatId] was.

Here is the code:

object[chatId] = {...object[chatId], messageToAdd}

messageToAdd has the following structure:

{"messageId3": {message: "newMessage", id: 2920222}}

How can I accomplish the task of appending to the object stored at the location chatId, instead of replacing it completely. Thanks.