Block JavaScript operations until a promise is resolved [duplicate]

I am trying to fetch a file into a synchronous class. But I cannot solve a problem that appeared: I need to get a return value of a function and store it into a variable, although I do not know when the promise will be fulfilled. Can someone explain a way to get my body?

function fetchSource(name: string): string {
    let source: string | null;
    getFileContents(name).then((response) => source = response);
    if (!source) { // <-- here we do not know at runtime what the value of this varaible is
        throw new Error("Cannot fetch shader source file " + name + ".");
    }
    return source;
}

JS – List of M+Y as links with mm/md/yyyy

I’m trying to build a simple list of links that shows the next 12 months, starting with the current month. The output would look like this:

<div class="dateLinks">
      <a href="example.com/ShowCalendar.asp?chdate=02/01/2024">February 2024</a>
</div>
<div class="dateLinks">
     <a href="example.com/ShowCalendar.asp?chdate=03/01/2024">March 2024</a>
</div>
....etc

The link text is the month and year and the href value is the first day of each month.

This is my code so far, but there has to be a more elegant way than just some long list of possible months, which needs to be updated at some point.

var theMonths = new Array("January 2024", "February 2024", "March 2024", "April 2024", "May 2024", "June 2024", "July 2024", "August 2024",
  "September 2024", "October 2024", "November 2024", "December 2024", "January 2025", "February 2025", "March 2025", "April 2025", "May 2025", "June 2025", "July 2025", "August 2025", "September 2025", "October 2025", "November 2025", "December 2025");

var theDates = new Array("1/1/2024", "2/1/2024", "3/1/2024", "4/1/2024", "5/1/2024", "June 2024", "July 2024", "August 2024",
  "September 2024", "October 2024", "November 2024", "December 2024", "January 2025", "February 2025", "March 2025", "April 2025", "May 2025", "June 2025", "July 2025", "August 2025", "September 2025", "October 2025", "November 2025", "December 2025");

var today = new Date();
var aMonth = today.getMonth();
var i;
for (i = 0; i < 12; i++) {
  document.write1('<div class="dateLinks"><a href="example.com/ShowCalendar.asp' + '?chdate=' + [aDate] + '">');
  document.writeln(theMonths[aMonth] + '</a></div>'); //here you can do whatever you want...
  aMonth++;
  if (aMonth > 11) {
    aMonth = 0;
  }
}

Append value to an existing key in Javascript

I’m getting key-value (text) data in chunks and need to create a new JSON obj without duplicating the keys in the resulting file.For e.g.

var jsonData = {};
var incoming = {
  "p1": "value1",
  "p2": "value2",
  "p3": "value3",
  "p1": "value4"
};

for (var key in incoming) {
  if (key in jsonData) {
    key = key + p[key]; //append text value to existing key value
    jsonData[key].push(incoming[key]);
  } else {
    jsonData[key] = [incoming[key]];
  }
}

console.log(JSON.stringify(jsonData));

Desired output:

{"p1":"**value1value4**","p2":"value2","p3":"value3"}

How do I can get the desired output?

Type error in typescript react-query and axios


import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import axios from "axios";

interface UserUrl {
  url: string;
}


function Upload() {
  const global_ping = "http://127.0.0.1:8000/";
  const [url, setUrl] = useState("");

  function short() {
    const data = { url: url };
    mutation.mutate(data);
  }
  function ChangeInInput(event: any) {
    setUrl(event.target.value);
  }

    const mutation = useMutation<any, Error, UserUrl>(
    async (userUrl: UserUrl) => {
        try {
        const response = await fetch(global_ping, {
            method: "POST",
            headers: {
            "Content-Type": "application/json",
            },
            body: JSON.stringify(userUrl),
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || "An error occurred");
        }

        return await response.json();
        } catch (error: any) {
        throw new Error(error.message || "An error occurred");
        }
    },
    {
        onSuccess: (data: any) => {
        console.log(data);
        console.log("Done");
        },
        onError: (error: Error) => {
        console.log(error);
        },
    }
    );




  return (
    <>
      <input
        placeholder="Enter The Url To Be Shortned"
        value={url}
        onChange={ChangeInInput}
      ></input>
      <button onClick={short}>Shorten!</button>
      <h1></h1>
    </>
  );
}

export default Upload;

so this is a component for my React.ts app. And I am specifically looking at:

const mutation = useMutation<any, Error, UserUrl>(
    async (userUrl: UserUrl) => {
        try {
        const response = await fetch(global_ping, {
            method: "POST",
            headers: {
            "Content-Type": "application/json",
            },
            body: JSON.stringify(userUrl),
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || "An error occurred");
        }

        return await response.json();
        } catch (error: any) {
        throw new Error(error.message || "An error occurred");
        }
    },
    {
        onSuccess: (data: any) => {
        console.log(data);
        console.log("Done");
        },
        onError: (error: Error) => {
        console.log(error);
        },
    }
    );

And I am getting and error in the mutation stating that:

Type '(userUrl: UserUrl) => Promise<any>' has no properties in common with type 'UseMutationOptions<any, Error, UserUrl, unknown>'.ts(2559)

how can I fix my code please help me this code above it is just making a http post request to a backend django, but I am not able to figure out how to solve this problem, can anyone please help me fix this problem?

animation with using gsap

There is such an animation, now when the site header touches the elements 01/08 02/08 03/08 04/08 05/08 06/08 07/08 08/08 we have one element painted over. But I need to make sure that when the logo is in the middle of the screen and at the same level with the text, the same animation occurs.

For example, our logo and text are at the same level in the middle of the screen – the scrolling element is painted over.
instead of painting over the element when we reach 01/08, we will calculate that they are on the same level

          <div class="slide group7 slide--autoheight slide-nav" id="services">
            <div class="slide__lines"></div>
            <div class="slide__inner">
              <div class="container">
                <div class="box row scol">
                  <div class="box__left">
                    <div class="text text--main">
                      <h2>IT solutions for your business tasks</h2>
                      <p class="g5">We create IT products, automate workflows and increase their efficiency, integrate advanced IT technologies for the
                        development of your company.</p>
                    </div>
                    <div class="text-snow">

                    <div class="text t1">
                      <div class="text__date">01/08</div>
                      <h3>IT consulting</h3>
                      <p class="g5">We analyze your business model, find weaknesses and identify growth points. We assess the readiness of your company to implement information architecture, develop a new business model or suggest how to optimize an existing one. We will show our strategic vision of how to solve business problems in order to ensure its sustainable development by introducing and modernizing the corporate IT infrastructure.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>
                    <div class="text t2">
                      <div class="text__date">02/08</div>
                      <h3>Custom Software Development Services</h3>
                      <p class="g5">Each company has various needs, so there is no ready-made standard solution that would suit everyone, and it is not desirable to implement something that does not fully solve the set tasks. We will develop a software product for the tasks of your business. We create an IT solution for unlimited scalability of your company, automation of routine processes and recurring tasks. We increase the efficiency of your employees so that you can use your human resources to achieve larger goals.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>

                    <div class="text t3">
                      <div class="text__date">03/08</div>
                      <h3>Enterprise Web Design and Development</h3>
                      <p class="g5">We develop multi-aspect web services, integrate them into company's IT architecture so that they form a single system and automate business workflow. We create corporate services, personal accounts, management systems with compound features, but a simple and convenient interface, to make web services work for people, increasing productivity, expanding business opportunities, assisting a company to grow and increase its profits.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>


                    <div class="text t4">
                      <div class="text__date">04/08</div>
                      <h3>React, Flutter, Ionic, and Native App Development</h3>
                      <p class="g5">GartLight develops cross-platform mobile applications using React, Flutter, Ionic frameworks. A feature of our products is high performance, speed, reliability, and ability to integrate with other corporate services. Take your business to a new digital level; optimize the company's internal tasks, speed up communication, increase customer loyalty and engagement.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>
                    <div class="text t5">
                      <div class="text__date">05/08</div>
                      <h3>Data Science, Machine Learning, and Artificial Intelligence</h3>
                      <p class="g5">Make management decisions based on figures and reliable data. We develop a platform comprising statistics and analytics. Our experts will assist to improve business processes and open up new opportunities for your company โ€“ to increase the speed of data collection, the accuracy of analysis by introducing intelligent algorithms into the infrastructure. An IT system will reduce manual operation, the number of errors and save time for employees.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>
                    
                    <div class="text t6">
                      <div class="text__date">06/08</div>
                      <h3>Cloud Integration and API Development</h3>
                      <p class="g5">Make your business safer, more efficient and more profitable with our certified experts who can help you to develop and implement the best IT cloud integration strategy. We will assist you to avoid data dispersion, increase the flexibility and performance of your company, improve the real-time operation of employees, and make updates using intelligent applications. We provide round-the-clock access to information and cyber security.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>
                    
                    
                    <div class="text t7">
                      <div class="text__date">07/08</div>
                      <h3>Identity Management</h3>
                      <p class="g5">In large companies whose information infrastructure is used not only by employees, but also by suppliers, partners, customers, it is difficult to effectively manage user accounts and access permissions. We automate identity management, including the full life cycle of employee accounts, information asset and access rights management processes. We eliminate multiple authentication, improve user experience. We improve the security and efficiency of information systems, reduce the administration time and costs, and reduce the number of recurring tasks.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>
                    
                    <div class="text t8">
                      <div class="text__date">08/08</div>
                      <h3>Cybersecurity</h3>
                      <p class="g5">We develop an information security system that is protected from any threats and meets international standards. We evaluate its resistance to internal and external threats, eliminate any vulnerabilities. We perform a risk assessment to determine the key targets for possible attacks. We protect your customers, partners, employees and corporate data from cybercriminals. Today, business viability depends on how properly your data is protected. By investing in information security, you reduce risks.</p>
                      <a href="#contacts" class="btn btn--link">Learn More</a>
                    </div>
                    </div>

                  </div>
                  <div class="box__right a-logo">
                    <svg viewBox="0 0 275 275" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M209.136 196.511L196.146 209.5C196.044 209.602 195.867 209.602 195.74 209.5L124.906 138.666C124.652 138.413 124.5 138.057 124.5 137.702H151.266C151.266 138.057 151.418 138.413 151.697 138.666L209.161 196.13C209.237 196.232 209.237 196.409 209.136 196.511Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l6" fill="url(#c)" />
                      <path
                        d="M229.559 128.214H172.475C171.714 128.214 171.004 128.518 170.446 129.051L162.809 136.687C162.53 136.966 162.378 137.322 162.403 137.677C162.403 138.032 162.53 138.387 162.809 138.666L170.446 146.303C170.979 146.835 171.714 147.14 172.475 147.14H229.584C229.686 147.14 229.736 147.064 229.736 146.988V128.366C229.736 128.29 229.66 128.214 229.559 128.214Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l7" fill="url(#b)" />
                      <path
                        d="M209.136 79.1726L160.145 128.188L151.672 136.636C151.393 136.916 151.24 137.296 151.266 137.677H124.475C124.449 137.296 124.602 136.916 124.881 136.636L195.74 65.777C195.842 65.6756 196.019 65.6756 196.146 65.777L209.136 78.7667C209.262 78.8935 209.262 79.0711 209.136 79.1726Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l8" fill="url(#a)" />
                      <path
                        d="M146.75 173.373V229.822C146.75 229.974 146.623 230.101 146.471 230.101H128.103C128.026 230.101 127.95 230.076 127.9 230C127.849 229.949 127.823 229.873 127.823 229.797L127.9 153.305L145.913 171.318C146.445 171.876 146.75 172.612 146.75 173.373Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l5" />
                      <path
                        d="M127.9 153.33V160.586L78.8078 209.526C78.7064 209.627 78.5288 209.627 78.4019 209.526L65.4123 196.536C65.3108 196.434 65.3108 196.257 65.4123 196.13L114.453 147.089H121.684L127.9 153.33Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l4" />
                      <path
                        d="M113.312 138.717L121.684 147.089H114.453L45.1414 147.115C45.0906 147.115 45.0653 147.115 45.0399 147.089C44.9384 147.038 44.8623 146.937 44.8623 146.835V128.467C44.8623 128.315 44.9892 128.188 45.1414 128.188H114.402H121.836L113.286 136.738C112.753 137.271 112.753 138.184 113.312 138.717Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l3" />
                      <path
                        d="M127.9 114.793V122.125L121.836 128.188H114.402L65.4123 79.1726C65.3108 79.0711 65.3108 78.8935 65.4123 78.7667L78.4273 65.777C78.5288 65.6756 78.7064 65.6756 78.8332 65.777L127.9 114.793Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l2" />
                      <path
                        d="M146.75 45.5061V102.082C146.75 102.843 146.445 103.579 145.913 104.112L127.9 122.125L127.849 45.5061C127.849 45.4554 127.874 45.3793 127.9 45.3285C127.95 45.2524 128.026 45.227 128.103 45.2017H146.471C146.623 45.2017 146.75 45.3285 146.75 45.5061Z"
                        stroke="#C1C1C1" stroke-width="0.439855" stroke-miterlimit="10" class="l-fill l1" /><defs>
                          <linearGradient display="none" id="a" x1="127.058" y1="172.858" x2="209.896" y2="171.118" gradientUnits="userSpaceOnUse">
                            <stop stop-color="#3DC7C7" />
                            <stop offset=".14" stop-color="#3CC3C7" />
                            <stop offset=".29" stop-color="#39B6C6" />
                            <stop offset=".45" stop-color="#34A1C4" />
                            <stop offset=".6" stop-color="#2E83C2" />
                            <stop offset=".76" stop-color="#255DBF" />
                            <stop offset=".92" stop-color="#1B2FBC" />
                            <stop offset="1" stop-color="#1515BA" />
                          </linearGradient>
                          <linearGradient display="none" id="b" x1="164.376" y1="136.991" x2="229.984" y2="132.832" gradientUnits="userSpaceOnUse">
                            <stop stop-color="#3DC7C7" />
                            <stop offset=".14" stop-color="#3CC3C7" />
                            <stop offset=".29" stop-color="#39B6C6" />
                            <stop offset=".45" stop-color="#34A1C4" />
                            <stop offset=".6" stop-color="#2E83C2" />
                            <stop offset=".76" stop-color="#255DBF" />
                            <stop offset=".92" stop-color="#1B2FBC" />
                            <stop offset="1" stop-color="#1515BA" />
                          </linearGradient>
                          <linearGradient display="none" id="c" x1="127.032" y1="100.907" x2="209.912" y2="99.168" gradientUnits="userSpaceOnUse">
                            <stop stop-color="#3DC7C7" />
                            <stop offset=".14" stop-color="#3CC3C7" />
                            <stop offset=".29" stop-color="#39B6C6" />
                            <stop offset=".45" stop-color="#34A1C4" />
                            <stop offset=".6" stop-color="#2E83C2" />
                            <stop offset=".76" stop-color="#255DBF" />
                            <stop offset=".92" stop-color="#1B2FBC" />
                            <stop offset="1" stop-color="#1515BA" />
                          </linearGradient>
                        </defs>
                    </svg>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="slide group7 slide--autoheight">
            <div class="slide__lines"></div>
            <div class="slide__inner nopad">
              <div class="container col">
                <div class="box row mcol">
                  <div class="box__left">
                    <h2>Some of <span class="gradient">Our Valued Customers</span></h2>
                    <ul class="our-clients-img">
                      <li><img src="images/logo-theworldbank.svg" alt="The World Bank"></li>
                      <li><img src="images/logo-hbo.svg" alt="HBO"></li>
                      <li><img src="images/logo-nbc.svg" alt="NBC"></li>
                      <li><img src="images/logo-deutschebank.svg" alt="Deutsche Bank"></li>
                      <li><img src="images/logo-moodys.svg" alt="Moody's"></li>
                      <li><img src="images/logo-bankofamerica.svg" alt="Bank of America"></li>
                      <li><img src="images/logo-citi.svg" alt="Citi"></li>
                      <li><img src="images/logo-aon.svg" alt="Aon"></li>
                      <li><img src="images/discovery.svg" alt="Discovery"></li>
                    </ul>
                  </div>
                  <div class="box__right iso">
                    <div class="text text--main">
                      <h2><span class="gradient">Our expertise</span> is confirmed by international ISO certification</h2>
                    </div>
                    <div class="text">
                      <img src="images/iso27001.png" alt="">
                      <p>ISO 27001 certificate officially confirms Gartlight's systematic approach to managing people, processes and IT systems by applying the secure risk management procedures.</p>
                    </div>
                    <div class="text">
                      <img src="images/iso9001.png" alt="">
                      <p>ISO 9001 certificate proves that Gartlight creates all solutions considering international quality and safety standards.</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
gsap.to(".a-logo", {
    scrollTrigger: {
        trigger: ".a-logo",
        marginTop: 120,
        start: "top top",
        end: () => `+=${document.querySelector(".a-logo").offsetHeight - 300}`,
        pin: true,
    }
});

const services = gsap.utils.toArray('.text-snow .text');

services.forEach((service, index) => {
    gsap.from(service, {
        scrollTrigger: {
            start: '-100px',
            end: 'top',
            trigger: service,
            scrub: true,
            onEnter: function () {
                document.querySelector('.a-logo').classList.add('l' + `${index + 1}`);
            },
            onEnterBack: function () {
                document.querySelector('.a-logo').classList.remove('l' + `${index + 1}`);
            }
        }
    });
});

I tried different methods, but I just canโ€™t figure out how to implement exactly the option I need.

Why doesn’t my manifest.json trigger the “Install Web App” modal?

here’s the manifest: https://twoshot.app/manifest.json

{
  "short_name": "TwoShot",
  "name": "TwoShot",
  "icons": [
    {
      "src": "logo.svg",
      "type": "image/svg"
    }
  ],
  "start_url": "/explore",
  "display": "standalone",
  "theme_color": "#ea0417",
  "background_color": "#1c1c1c",
  "scope": "/",
  "orientation": "landscape-primary"
}

When I open https://twoshot.app, no installation options show up ๐Ÿ™

Writing a parser for JavaScript’s console

I want to be able to write a parser of some sort that takes the values from a JS console.log and formats them similar to Chrome DevTools. I can’t seem to find any libraries that do this out of the box.

Does anyone know the internals of how Chrome formats and displays the output? If there’s a nested object, I’d like to format key/values corresponding to their underlying types.

something like this

Are there any implemented in JavaScript? Other languages? I know I can hook into the console/evaluate code for an output, but don’t know where to start with parsing.

Ideally this outputs some sort of AST for JS which can be passed around.

I tried digging through the v8 source, Node’s inspect function, Bun’s console, and I see a general idea, but I am curious if there’s already a library for this. I am not even sure what to Google.

Unable to aggregate sum of a field after including lookup for another collection where foreign collection field == a given value

I have 2 mongo collections – Transaction and Supplier. I am trying to do an aggregation of the total value of transactions both outside and inside of a given country so I can compare imports vs domestic purchases. When I join the suppliers collection to transactions, my match condition seems to be getting ignored and I am returned the total sum of all transactions. What am I doing wrong?

This is my aggregation, attempting sum of all transactions where location.country == uk

let aggs = [
        {
            $match : { type : "out" },
        },
        {
            $lookup: {
                from:"suppliers",
                let: { country : "$location.country" },
                localField:"supplier",
                foreignField:"_id",
                as:"suppliers",
                pipeline: [
                    {
                        $match: {
                            $expr: {
                                $eq: [ '$suppliers.location.country', "United Kingdom" ]
                            }
                        },
                    },
                ]
            }
        },
        {
            $group: {
                _id: null,
                total: { $sum : { $divide: ['$price', 100] } }
            },
        }
    ];

This is my Transaction schema


const TransactionSchema = mongoose.Schema({
    item: {type: String, required: true },
    category: {type: String },
    type: { type: String, enum: ['in', 'out'] },
    price: { type: Number, required: true, get: getPrice, set: setPrice },
    description: { type: String },
    supplier: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: "Supplier"
    },
    customer: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: "Customer"
    },
    project: { type: String },
    invoice_ref: { type: String },
    payment_method: { type: String },
    parent_transaction: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: "Transaction"
    },
    date: { type: Date },
    createdAt: { type: Date, default: Date.now(), immutable: true },
    updatedAt: { type: Date, default: Date.now() }
});

This is my suppliers schema

const SupplierSchema = mongoose.Schema({
    name: {
        type: String, unique: true
    },
    description: { type: String },
    website: { type: String },
    email: { type: String },
    location: {
        address: { type: String },
        town: { type: String },
        county: { type: String },
        postcode: { type: String },
        country: { type: String }
    }
});

Onclick Events in Titanium Require Waiting Several Seconds Between Clicks

I’ve got a mobile app written using Titanium SDK. There are various views that have click events. Some are assigned through the XML view using onClick="functionName", and others are assigned using $.viewId.addEventListener('click', function(){}).

Either way, if I click on a view once, I have to wait for anywhere from five to forty five seconds before it will allow me to click on it to perform the function again. This is for all of the pages that use native views.

Clicking on a second different view works just fine, the first time. It’s only when I click the same view a second time that I notice the delay.

The pages that use WebViews do not have this problem. So native Titanium is less responsive than WebViews with HTML and JavaScript.

This problem is present for both 12.1.0.RC and 12.2.1.GA.

Is this an intentional feature or a know bug in Titanium SDK?

How can I make the click events work for a second click more rapidly?

Why is the main process slow but not when I’m streaming data inside a render process?

Video

render.js:

async function getVideoSources() {
  const inputSources = await window.electronAPI.videoSelectBtnClicked();
}

async function selectSource(source) {
  videoSelectBtn.innerText = source.name;
  const constraints = {
    audio: false,
    video: {
      mandatory: {
        chromeMediaSource: "desktop",
        chromeMediaSourceId: source.id,
      },
    },
  };
  const stream = await navigator.mediaDevices.getUserMedia(constraints);
  videoElement.srcObject = stream;
  videoElement.play();
}

window.electronAPI.sourceSelected((value) => {
  selectSource(value);
});

preload.js:

const { contextBridge, ipcRenderer } = require("electron/renderer");

contextBridge.exposeInMainWorld("electronAPI", {
  videoSelectBtnClicked: () => ipcRenderer.send("videoSelectBtn-clicked"),
  sourceSelected: (callback) =>
    ipcRenderer.on("source-selected", (_event, value) => callback(value)),
});

index.js:

async function selectSource(source) {
  await mainWindow.webContents.send("source-selected", source);
}

async function handleVideoSelection() {
  const inputSources = await desktopCapturer.getSources({
    types: ["window", "screen"],
  });
  const videoOptionsMenu = Menu.buildFromTemplate(
    inputSources.map((source) => {
      return {
        label: source.name,
        click: () => selectSource(source),
      };
    })
  );
  videoOptionsMenu.popup();
}
ipcMain.on("videoSelectBtn-clicked", handleVideoSelection);

The delay is happening during the dektopCapturer.getSources, but when the render is streaming data the delay is significantly decreased, is there a way to fix this delay?

Is there a method to fix this error? => (Something went wrong TypeError: res.json is not a function)

When I fetch a object to add to my mongodb

const response = await fetch("/api/contact", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
    "Content-Type": "application/json",
    },
});

I get [Something went wrong TypeError: res.json is not a function] here

import React from "react";
import { NextResponse, NextRequest } from "next/server";
import wordModel from "../../../models/wordModel";
import mongoose from "mongoose";

export async function POST(req, res) {
  const MONGO_URI = process.env.MONGO_URI;
  try{
    await mongoose.connect(MONGO_URI)
    console.log("It's good");
    const word = await wordModel.create(req.body);
    res.json({ word }); 
  } catch(error) {
    console.log("Something went wrong", error);
    return new Response;
  }
}

and then in my db appear a document that contain random numbers and letters

How to create an element in just one div with the same class of another

I’m creating a tic-tac-toe game where each cell is another tic-tac-toe game, so I created a script that creates html elements, but now I’m going to create an svg of an X or O in the cell that the player clicked on, so I tried to do it like onclick=”x()” but when i click in whatever cell, the svg element is created in the frist cell. (I also didn’t check if there alread is an X or O in the cell).

js:

<script>
    function create_elements_from_html(n, html){
        const template = document.createElement("template")
        let htmlaux = ``
        for (a = 0; a < n; a += 1){
            htmlaux += html
        }

        template.innerHTML = htmlaux
        return template.content;
    }
    let turn = "x"
    function play(){
        if (turn == "x"){
                let x = create_elements_from_html(1, `<svg viewBox="0 0 100 100"> <path class="x_cell_path" d="M 10 10 L 90 90 Z M 10 90 L 90 10"> </svg>`)
                turn = "o"
                return document.querySelector(".cell").appendChild(x)
        }
        else{
                let o = create_elements_from_html(1, `<svg viewBox="0 0 100 100"> <circle class="o_cell_path" r="40" cx="50" cy="50"> </svg>`)
                return document.querySelector(".cell").appendChild(o)
                turn = "x"
        }
    }

    let big_board = create_elements_from_html(1, 
        `<div class="big_board">

            <svg class="small_board_svg" viewBox="0 0 100 100">
                <path class="big_board_path" d="M 33.33333 0 l 0 100 M 66.66666 0 l 0 100 M 0 33.33333 l 100 0 M 0 66.66666 l 100 0">

            </svg>
        </div>`)

    document.body.appendChild(big_board)

    let small_board = create_elements_from_html(9, 
        `<div class="small_board">
            <svg class="small_board_svg" viewBox="0 0 100 100">

                <path class="small_board_path" d="M 33.33333 0 l 0 100 M 66.66666 0 l 0 100 M 0 33.33333 l 100 0 M 0 66.66666 l 100 0">

            </svg>
        </div>`)
    document.querySelector(".big_board").appendChild(small_board)

    for (let i = 0; i < 9; i++) {
        let cell = create_elements_from_html(1, `
        <div class="cell" data-cell onclick="play()">
        </div>`)
        document.querySelectorAll(".small_board").forEach((board) => board.appendChild(cell.cloneNode(true)))
    }
</script>

I want that when I click in the [0, 1] cell, the [0, 1] cell is filled with a X or O, but now that isn’t woking

Vue 3 – How can I create v-models on deep arrays or objects?

I need to create several v-models of random properties of a deep array (arrays/objects attributes position can be changed anytime). I managed to do what I want as follows. However, there will be several fields to be rendered in different places on the page, so a v-for is out of consideration. Is it possible to simplify this code?

<template>
  <div class="builder">
    <div class="sidebar">
      <div class="block">
        <input v-model="template[headTagIndex].children[headTagAttributesIndex].children[headTagAttributesAllIndex].attributes['font-family']" placeholder="Fonte geral" type="text">
      </div>
    </div>
    <div class="editor">
      <div v-if="compiledTemplate" v-html="compiledTemplate.html"/>
      <div v-else>Loading</div>
    </div>
    <div class="ads"/>
  </div>
</template>

<script setup>
const {$mjml} = useNuxtApp()

const template = ref([
  {
    "tagName": "mj-head",
    "children": [
      {
        "tagName": "mj-attributes",
        "children": [
          {
            "tagName": "mj-all",
            "attributes": {
              "font-family": "Comic sans-serif"
            }
          }
        ]
      }
    ]
  },
  {
    "tagName": "mj-body",
    "children": [
      {
        "tagName": "mj-section",
        "attributes": {
          "background-color": "red"
        },
        "children": [
          {
            "tagName": "mj-column",
            "attributes": {
              "padding-top": "100px",
              "padding-bottom": "100px"
            },
            "children": [
              {
                "tagName": "mj-text",
                "attributes": {
                  "align": "center",
                  "color": "#F45E43"
                },
                "content": "Testing component"
              }
            ]
          }
        ]
      },
      {
        "tagName": "mj-section",
        "attributes": {
          "full-width": "full-width",
          "background-color": "blue"
        },
        "children": [
          {
            "tagName": "mj-column",
            "attributes": {
              "padding-top": "100px",
              "padding-bottom": "100px"
            },
            "children": [
              {
                "tagName": "mj-text",
                "attributes": {
                  "align": "center",
                  "color": "#F45E43"
                },
                "content": "Testing component"
              }
            ]
          }
        ]
      },
      {
        "tagName": "mj-section",
        "attributes": {
          "background-color": "pink"
        },
        "children": [
          {
            "tagName": "mj-column",
            "attributes": {
              "padding-top": "100px",
              "padding-bottom": "100px"
            },
            "children": [
              {
                "tagName": "mj-text",
                "attributes": {
                  "align": "center",
                  "color": "#F45E43"
                },
                "content": "Testing component"
              }
            ]
          }
        ]
      },
      {
        "tagName": "mj-section",
        "attributes": {
          "full-width": "full-width",
          "background-color": "teal"
        },
        "children": [
          {
            "tagName": "mj-column",
            "attributes": {
              "padding-top": "100px",
              "padding-bottom": "100px"
            },
            "children": [
              {
                "tagName": "mj-text",
                "attributes": {
                  "align": "center",
                  "color": "#F45E43"
                },
                "content": "Testing component"
              }
            ]
          }
        ]
      }
    ]
  }
])

const headTagIndex = template.value.findIndex((tag) => tag.tagName === 'mj-head')
console.log(headTagIndex)
const headTagAttributesIndex = template.value[headTagIndex].children.findIndex((tag) => tag.tagName === 'mj-attributes')
console.log(headTagAttributesIndex)
const headTagAttributesAllIndex = template.value[headTagIndex].children[headTagAttributesIndex].children.findIndex((tag) => tag.tagName === 'mj-all')
console.log(headTagAttributesAllIndex)

const compiledTemplate = computed(() => $mjml({
  "tagName": "mjml",
  "children": template.value
}))
</script>

The parts that need to be optimized are:

v-model="template[headTagIndex].children[headTagAttributesIndex].children[headTagAttributesAllIndex].attributes['font-family']"

And:

const headTagIndex = template.value.findIndex((tag) => tag.tagName === 'mj-head')
console.log(headTagIndex)
const headTagAttributesIndex = template.value[headTagIndex].children.findIndex((tag) => tag.tagName === 'mj-attributes')
console.log(headTagAttributesIndex)
const headTagAttributesAllIndex = template.value[headTagIndex].children[headTagAttributesIndex].children.findIndex((tag) => tag.tagName === 'mj-all')
console.log(headTagAttributesAllIndex)```

what alternate to res.cookie() can i use to send token to the frontend?

So ive been using res.cookie() to send the user’s token to the frontend for a while, however, i’ve only ever tested it locally. I recently wanted to host my mern stack app on render.com and it turns out that i can’t use res.cookie() to send the token to the frontend because cookies dont set within sub domains, which is what render.com gives you i.e “website-name.render.com”. I would have to buy a custom domain name which i cant afford yet. This is what i mean

Sending the token to the frontend using res.cookie:

const register = async (req, res) => {
    const user = await User.create({...req.body})

    const token = user.createJWT()
    res.status(StatusCodes.CREATED).cookie('token', token).json({ name: user.name})
}

Getting the token using an auth middleware:

const authMiddleware = async (req, res, next) => {
    const {token} = req.cookies

    if(token){
        try{

            const {userId, name} = jwt.verify(token, process.env.JWT_SECRET)
            req.user = {userId, name}  
            next()
        }
        catch(error){
            throw new UnauthenticatedError('Authentication invalid')
        }
    }else{
        throw new UnauthenticatedError('no token')
    }

    
}

Essentially, this code above, which works fine locally, doesnt work when i host it on render.com, I am currently getting the “no token” error. Which brings me to my question, if i cant use cookies, whats my alternative here or am i forced to pay for a custom domain even though this is a personal project?