Calculo de Frete / Freight Calculation

Estou programando em nextjs e estou com dificuldade na funcionalidade de calcular frete de um ecommerce que estou fazendo, olhe a documentação do correios, mas achei muito massiva, e a do melhor envio não consegui implementar.

Alguem poderia me ajudar a fazer essa implantação ? Sugerindo video, documentação ou dando um help de alguma maneira…

English
I’m programming in nextjs and I’m having difficulty with the functionality of calculating shipping for an ecommerce I’m doing, look at the documentation of the post office, but I found it too massive, and the best shipping I couldn’t implement.

Could someone help me to do this implementation? Suggesting video, documentation or giving a help in some way…

Já tentei implantar com a documentação do correios e do melhor envio e não consegui, então estou na estaca 0 novamente kkk não sei o que fazer.

English
I’ve tried to implement it with the documentation of the post office and the best shipping and I couldn’t, so I’m at stake 0 again lol I don’t know what to do.

Calling Python Api from javascript file not working

While trying to retrieve data from the python api i created below, i get ‘Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)’ error line 3 of the js file. I tried restarting and going through the process again but that resulted in the same thing.

app.js

/*async function fetchdata(){*/
    try {
        const response = await fetch('http://127.0.0.1:5000/api/get_data');
        const data = await response.json();  // Convert response to JSON

        console.log('Data:', data);

        // return data; 
    } catch (error) {
        console.error('Error:', error);
    }
/*}
fetchdata();*/

app.py

@app.route('/api/get_data', methods=['GET'])
def get_data():
    form = loginForm()
    print('hello')
    data = {
        "ownsPython": str(User.query.filter_by(username = form.username.data).first().javascriptOwner),
        "ownsJava" : str(User.query.filter_by(username = form.username.data).first().pythonOwner),
        "ownsPython" : str(User.query.filter_by(username = form.username.data).first().ownsJavascript)
    }
    return jsonify(data)

React App won’t render after importing auth from firebase

Vite, React, and Tailwind.
When I ran my project on the browser with auth from firebase imported, my app wouldn’t load. Now, what I realized is that when I put the import auth from 'firebase/auth' at the end of the code the app will still load. So, I assume that the import takes more time and the solution is something correlated with asynchronous importing. Alas, I still haven’t founded the right code to fix it.

Here’s my code:

firebase.jsx

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { getAuth } from "firebase/auth";

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "####",
  authDomain: "####.firebaseapp.com",
  projectId: "###",
  storageBucket: "###",
  messagingSenderId: "####",
  appId: "####",
  measurementId: "####"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const auth = getAuth();

SignUp.jsx

This is where I want to put the sign up functioning. So, when line one is inputted, the app would crash. However, when it is put on the last line of code, it won’t. I wouldn’t be able to write the code properly if the import was in the last line.

import auth from '../firebase/firebase'
export default function SignUp(){
    return (
        <div className="rounded-xl w-2/5 flex-1 absolute h-2/4 bg-dark items-center left-2/4 top-2/4 -translate-y-2/4 -translate-x-2/4 ">
            <form action="">
                <h2 className="text-white text-3xl flex-1 font-mono font-bold text-center">Sign Up</h2>
                <input type="text" /> 
            </form>
        </div>
    )
}

I tried asynchronous importing using this syntax that I found on stackexchange but it didn’t work.

(async () => {

  const { getAuth } = await import('firebase/auth');

})();

I also tried to put the import { getAuth } from "firebase/auth"; on the SignUp file and continue everything from there but still didn’t work.

How to share an access with Authorized users in Apps Script Web App without them giving access to Google Sheets?

How to give permission to Authorized users to use the apps script web app without them giving access the google sheets? I am so confused right now. Please help me…
So I also create AuthorizedUsers sheet where there is the list of the emails of the authorized people I want to give access. So when they click the link of the web app the authorized users should be redirected to the index page while the non authorized users should get the message “You are not authorized to access this application.” but the issue here is that, when the other users tried to access the web app even if their email is in the AuthorizedUsers sheet they are still getting a message like this “Exception: You do not have permission to access the requested document. (line 39, file “Code”)”

This is the code I tried.
In the manage deployments I’ve set the following:

Execute as:
*User accessing the web app *

Who has access:
Anyone with Google account

Code.gs

function doGet(e) {
  // Check if the event object e is defined and has parameter
  var page = (e && e.parameter) ? e.parameter.page || 'index' : 'index'; // Default to 'index' if no page is specified or e is undefined

  var userEmail = Session.getActiveUser().getEmail();
  Logger.log("User Email from Session: " + userEmail); // Debugging line

  if (isAuthorized(userEmail)) {
    logUserEmail(userEmail);
    return HtmlService.createTemplateFromFile(page).evaluate();
  } else {
    // Redirect to an unauthorized access page or show an error message
    return HtmlService.createHtmlOutput("You are not authorized to access this application.");
  }
}

function loadIndex(e) {
  // Check if the event object e is defined and has parameter
  var page = (e && e.parameter) ? e.parameter.page || 'index' : 'index'; // Default to 'index' if no page is specified or e is undefined

  var userEmail = Session.getActiveUser().getEmail();
  Logger.log("User Email from Session: " + userEmail); // Debugging line

  if (isAuthorized(userEmail)) {
    logUserEmail(userEmail);
    return HtmlService.createTemplateFromFile(page).evaluate();
  } else {
    // Redirect to an unauthorized access page or show an error message
    return HtmlService.createHtmlOutput("You are not authorized to access this application.");
  }
}

function logUserEmail(email) {
  var email = Session.getActiveUser().getEmail();
  Logger.log("User Email: " + email);
}

function isAuthorized(email) {
  var sheet = SpreadsheetApp.openById('13dStidKhr3EcvDUZTZWxFVc5N2rQkfbGySclp0JqNTI').getSheetByName('AuthorizedUsers');
  var data = sheet.getRange('A:A').getValues(); // Get all email addresses in column A
  var emails = data.flat().filter(String); // Flatten and remove empty values

  Logger.log("Authorized Emails: " + JSON.stringify(emails)); // Debugging line
  return emails.includes(email);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

I also tried changing the manage deployments I’ve changed it into:

Execute as:
Me

Who has access:
Anyone with Google account

and changed the Session.getActiveUser into Session.getEffectiveUser but when the other users tried to access the web app even if they do not belong to AuthorizedUsers they can still access the web app.

Trying to mock AdvancedMarkerElement from google.maps.MarkerLibrary

We have been banging our heads against the wall trying to test the AdvancedMarkerElement from the google maps api. We replaced google.maps.Markers with AdvancedMarkerElement. The tests we had originally were using @googlemaps/jest-mocks' and we mocked the listener and then called it directly using addListenerSpy.mock.calls[0][1]() and then assert that the proper calls were made. Below is the test which was working with Markers

/* global jest context */
import { render, waitFor } from '@testing-library/react'
import { initialize } from '@googlemaps/jest-mocks'
import '@googlemaps/react-wrapper'

import { useSessionContext } from 'hooks/SessionContext'

import Map from 'pages/Dashboard/CriticalAndMajorAlertsMapCard/Map'

jest.mock('hooks/SessionContext')

jest.mock('@googlemaps/markerclusterer', () => ({
  ...jest.requireActual('@googlemaps/markerclusterer'),
  MarkerClusterer: jest.fn().mockImplementation(() => {})
}))

//  mocking useLayoutEffect to use useEffect useLayoutEffect is intended to be used within a browser like environment
//  and jest runs test in node .env by default which doesn't provide a browser DOM.
//  https://stackoverflow.com/questions/58070996/how-to-fix-the-warning-uselayouteffect-does-nothing-on-the-server
//  https://react.dev/reference/react/useLayoutEffect#im-getting-an-error-uselayouteffect-does-nothing-on-the-server

jest.mock('react', () => ({
  ...jest.requireActual('react'),
  useLayoutEffect: jest.requireActual('react').useEffect
}))

const dealer = Object.freeze({
  dealerId: 1,
  latitude: 40.15,
  longitude: -111.11
})

const devices = Object.freeze({
  deviceId: '12345ABCD',
  criticalAlertCount: 1,
  majorAlertCount: 1,
  sdaMajorAlertCount: 0
})

const customersWithLocation = Object.freeze(
  [{
    customerId: 1,
    dealerId: 2,
    latitude: 35.01,
    longitude: -113.45,
    devices: [devices]
  }]
)

describe('Map', () => {
  context('when map loads', () => {
    const addListenerSpy = jest.fn()
    const openInfoWindowSpy = jest.fn()
    const setContentinfoWindowSpy = jest.fn()

    beforeEach(() => {
      useSessionContext.mockReturnValue({
        session: dealer
      })

      initialize()
      window.google.maps.Marker = jest.fn().mockImplementation(() => {
        return {
          addListener: addListenerSpy
        }
      })

      window.google.maps.InfoWindow = jest.fn().mockImplementation(() => {
        return {
          setContent: setContentinfoWindowSpy,
          open: openInfoWindowSpy
        }
      })
    })

    describe('when user clicks on the customer marker', () => {
      it('opens info window for customer ', async () => {
        render(<Map customersWithLocation={customersWithLocation} />)

        addListenerSpy.mock.calls[0][1]()

        await waitFor(() => {
          expect(setContentinfoWindowSpy).toHaveBeenCalledTimes(1)
          expect(openInfoWindowSpy).toHaveBeenCalledTimes(1)
        })
      })
    })
  })
})

When we switched to using AdvancedMarkerElement we had to import the library like so:

 const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker')) as google.maps.MarkerLibrary

We could not figure out how to mock this using jest mocks so what we wound up doing is creating a file that contains this functionality and then are trying to mock the file we just implemented. The AdvancedMarkerElement importer file is:

export const importAdvancedMarkerElement = async () => {
  const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker')) as google.maps.MarkerLibrary
  return AdvancedMarkerElement
}

We have tried mocking the above like so:

jest.mock('pages/Dashboard/CriticalAndMajorAlertsMapCard/AdvancedMarkerElement', () => {
  return {
    importAdvancedMarkerElement: jest.fn().mockImplementation(() => {
      return {
        addListener: jest.fn()
      }
    })
  }
})

But are now getting the following error when running:

    TypeError: AdvancedMarkerElement is not a constructor

      54 |           }
      55 |
    > 56 |           const marker = new AdvancedMarkerElement({

Any help with testing this functionality would be greatly appreciated.

Paypal PayoutsAAC login stopped working with error “Window does not have a parent”

I am using the paypal payouts AAC api, and it was working fine until last week. Now after the user logs in, the login window just sits on a blank page. I checked the console and it has this error:

post-robot.ie.min.js:1 Uncaught Error: Window does not have a parent
at post-robot.ie.min.js:1:20565
at new e (post-robot.ie.min.js:1:35923)
at r.sendToParent (post-robot.ie.min.js:1:20523)
at HTMLDocument.<anonymous> (advConnectRedirect.js:21:13)

How to specify the format for citations using citation-js? Is there a plugin for CSL?

Although Cite.format allows you to specify a template, it doesn’t seem to use it. According to the documentation,

enter image description here

I assume that means that it uses code from {citeproc-js}. Citation-JS has plugins. Is one of them used for formatting the citations via CSL? I can’t find any examples.

The word output_formats isn’t actually a link. There is a tutorial for Outputs, but it contains almost no information.

        const Cite = require('citation-js');

        // Sample BibTeX string for demonstration
        const bibtex = `
        @article{Loomes2017,
            title = {Loomes Title},
            author = {Loomes, Rachel and Hull, Laura and Mandy, William Polmear Locke},
            date = {2017-06},
            journaltitle = {Journal of the American Academy of Child and Adolescent Psychiatry},
            volume = {56},
            number = {6},
            pages = {466--474},
            doi = {10.1016/j.jaac.2017.03.013}
        }
        @article{Mantzalas2022,
            title = {Mantzalas Title},
            author = {Mantzalas, Jane and Richdale, Amanda L. and Adikari, Achini and Lowe, Jennifer and Dissanayake, Cheryl},
            date = {2022-03},
            journaltitle = {Autism in Adulthood},
            volume = {4},
            number = {1},
            pages = {52--65},
            doi = {10.1089/aut.2021.0021}
        }
        `;

        // Create the citation-js object
        const library = new Cite(bibtex);

        let single_citation = "Loomes2017";
        let double_citation = "Loomes2017,Mantzalas2022";

        let single_inline_apa = library.format('citation', {
            entry: single_citation,
            format: 'html',
            template: "apa",
            lang: 'en-US'
        });

        console.log(`single inline APA: ${single_inline_apa}`);

        let double_inline_apa = 
            double_citation
            .split(",")
            .map(x => x.trim())
            .map(x => library.format('citation', {
                entry: x,
                format: 'html',
                template: "apa",
                lang: 'en-US'
                })
            )
            .join(",")

        console.log(`double inline APA: ${double_inline_apa}`);

        let single_inline_ama = library.format('citation', {
            entry: single_citation,
            format: 'html',
            template: "apa",
            lang: 'en-US'
        });

        console.log(`single inline AMA: ${single_inline_ama}`);

        let double_inline_ama = 
            double_citation
            .split(",")
            .map(x => x.trim())
            .map(x => library.format('citation', {
                entry: x,
                format: 'html',
                template: "ama",
                lang: 'en-US'
                })
            )
            .join(",")

        console.log(`double inline AMA: ${double_inline_ama}`);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Citation-JS Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/citation-js/0.7.14/citation.js"></script>
</head>
<body>
    <div id="content"></div>
</body>
</html>

Unable to run built/transpiled Typescript applications with Node – Tsc x Babel

My question is about a problem that I’m actually facing but I think I’m still missing some concepts about transpiling Typescript into Javascript. Basically what I’m planning to do in my application is to develop it using Typescript, build it to Javascript and run it with PM2. It’s an application used for studies purposes only. Repository

I guess the main problem here is ES modules over CommonJS.

In my application I’ve set up a base directory in tsconfig.json so my imports look like this:

import SignUp from "src/application/services/signup";
import UserRepository from "src/infra/repositories/account-repository";
import PasswordHasher from "src/infra/security/hasher";
import SignUpController from "src/presentation/controllers/sign-up-controller";

export default class SignUpFactory {
  static makeUseCase(): SignUp {
    const userRepository = new UserRepository();
    return new SignUp(userRepository, new PasswordHasher());
  }

  static makeController(): SignUpController {
    return new SignUpController(this.makeUseCase());
  }
}

Basically my imports are all set up to an absolute path.

When I transpile the project, it turns to keep the absolute paths:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _signup = _interopRequireDefault(require("src/application/services/signup"));
var _accountRepository = _interopRequireDefault(require("src/infra/repositories/account-repository"));
var _hasher = _interopRequireDefault(require("src/infra/security/hasher"));
var _signUpController = _interopRequireDefault(require("src/presentation/controllers/sign-up-controller"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
class SignUpFactory {
  static makeUseCase() {
    const userRepository = new _accountRepository.default();
    return new _signup.default(userRepository, new _hasher.default());
  }
  static makeController() {
    return new _signUpController.default(this.makeUseCase());
  }
}
exports.default = SignUpFactory;

And when running using node dist/server.js it gives me an error telling me the modules weren’t found.

node:internal/modules/cjs/loader:1148
  throw err;
  ^

Error: Cannot find module 'src/application/services/get-account'
Require stack:
- /home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/factories/get-account-factory.js
- /home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/app/routes.js
- /home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/app/app.js
- /home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/server.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1145:15)
    at Module._load (node:internal/modules/cjs/loader:986:27)
    at Module.require (node:internal/modules/cjs/loader:1233:19)
    at require (node:internal/modules/helpers:179:18)
    at Object.<anonymous> (/home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/factories/get-account-factory.js:7:42)
    at Module._compile (node:internal/modules/cjs/loader:1358:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
    at Module.load (node:internal/modules/cjs/loader:1208:32)
    at Module._load (node:internal/modules/cjs/loader:1024:12)
    at Module.require (node:internal/modules/cjs/loader:1233:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/factories/get-account-factory.js',
    '/home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/app/routes.js',
    '/home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/main/app/app.js',
    '/home/gabriel/PROJETOS/LEARNING/branas-io/account/dist/server.js'
  ]
}

Node.js v20.14.0

I tried to use the default tsc transpiler and Babel but both ways I get the same result.

babel.config.json

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ],
    "@babel/preset-typescript"
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "root": [
          "./src"
        ]
      }
    ]
  ],
  "ignore": [
    "**/*.spec.ts"
  ]
}

tsconfig.json

{
  "compilerOptions": {
    "lib": [
      "ESNext",
      "DOM"
    ],
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Node",
    "moduleDetection": "force",
    "esModuleInterop": true,
    "allowJs": true,
    "jsx": "react-jsx",
    "verbatimModuleSyntax": false,
    "baseUrl": ".",
    "rootDir": "./src",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "types": [
      "vitest/globals"
    ],
    "outDir": "dist",
    "removeComments": false,
  },
  "include": [
    "src/**/*.ts",
  ],
  "exclude": [
    "node_modules",
    "dist",
    "tests",
    "vitest.config.ts",
  ]
}

I’m looking for a solution but if you have some references on ESModules and CommonJS in Typescript transpilation I appreciate it.

Well, I expected my built application running either with node or pm2. I’m planning to run this process in a Docker container so I can keep on developing and running automated tests in other microservices from the whole project.

As I said before I tried to build it using tsc and babel but got the same error in both.

Should I use multiple map functions or just one

I’m currently using an NFL Api to create an analytics website. I’m trying to map through 3 separate arrays in my react component. One of the arrays is holding names of players I retrieved from the API fetchFullNames. Another array is holding hrefs of the player’s headshots fetchImages. And then one array’s holding the id for each player quarterbacks. In my return statement is where I am trying to map through each of these arrays displaying 5 cards, one for each player containing their name and headshot. My code right now is displaying the same player’s name multiple times and is also displaying the same player’s headshot multiple times. I’m wondering if I should be using just one map function for all the data in my return statement.

This is the code I’m currently working with:

import { Link } from "react-router-dom";
import _navbar from "../../NavBar/navbar";
import React, { useEffect, useState } from "react";
import styles from "./card.module.css";

const quarterbacks = [3139477, 4241479, 3918298, 3915511, 2577417];
  const fetchFullName = async (id) => {
    const res = await fetch(
      `https://nfl-api-data.p.rapidapi.com/nfl-ath-fullinfo?id=${encodeURIComponent(id)}`,
      {
        headers: {
          "x-rapidapi-key": "secret key",
          "x-rapidapi-host": "nfl-api-data.p.rapidapi.com",
        },
      },
    );
    if (!res.ok) {
      throw new Error(`Name lookup for id '${id}' failed`);
    }
    return (await res.json()).athlete.fullName;

  };
  
  // returns an array of {id, name} objects
  const fetchFullNames = async (ids) =>
    Promise.all(ids.map(async (id) => ({ id, name: await fetchFullName(id) })));


  const fetchImage = async (id) => {
    const res = await fetch(
      `https://nfl-api-data.p.rapidapi.com/nfl-ath-img?id=${encodeURIComponent(id)}`,
        {
          headers: {
            "x-rapidapi-key": "secret key",
            "x-rapidapi-host": "nfl-api-data.p.rapidapi.com",
          },
        },
      );
      if(!res.ok) {
        throw new Error(`Image lookup for id '${id}' failed`);
        
      }
      return (await res.json()).image.href;
    
  }
  // Returns an array of the href for each player 
  const fetchImages = (ids) => 
    Promise.all(ids.map(async (id) => ({image : await fetchImage(id)})));
  

  
  

  export default function _quarterbacksPage() {
    const [names, setNames] = useState([]);
    const [images, setImages] = useState([]);
  
    useEffect(() => {
      fetchFullNames(quarterbacks).then(setNames).catch(console.error);
      fetchImages(quarterbacks).then(setImages).catch(console.error);
    }, []);
  
    return (
      <>
        <_navbar />
        <div className={styles.cards}>
          {quarterbacks.map(() => (
            <div className={styles.card}>   
              {images.map(({image}) => (             
                <img src={image} key={image} alt="player picture"/>
              ))}
              {names.map(({id, name }) => (
                <Link className={styles.cardText} key={id} to={`/quarterback/${id}`}>
                  {name}
                </Link>
              ))}
            </div>
          ))}
        </div>
          
      </>
    );
  }

React useEffect() not executing before page render

I’m trying to pull postcode information and display it on my react app. The code so far looks as such:

const UKPar = () => {

    postcode = "SW1A2AA"
    const [ukPostcodeData, setUKPostcodeData] = useState({});

    useEffect(() => {
        fetch('https://api.postcodes.io/postcodes/' + postcode)
           .then((res) => res.json())
           .then((data) => {
              console.log(data);
              setUKPostcodeData(data);
           })
           .catch((err) => {
              console.log(err.message);
           });
    }, [postcode]);

    return(...)
}
export default UKPar;

This works fine and I can see that the data is displayed in the browser log as so:

{
    "status": 200,
    "result": {
        "postcode": "SW1A 2AA",
        "quality": 1,
        "eastings": 530047,
        "northings": 179951,
        "country": "England",
        "nhs_ha": "London",
        "longitude": -0.127695,
        "latitude": 51.50354,
        "european_electoral_region": "London",
        "primary_care_trust": "Westminster",
        "region": "London",
        "lsoa": "Westminster 018C",
        "msoa": "Westminster 018",
        "incode": "2AA",
        "outcode": "SW1A",
        "parliamentary_constituency": "Cities of London and Westminster",
        "parliamentary_constituency_2024": "Cities of London and Westminster",
        "admin_district": "Westminster",
        "parish": "Westminster, unparished area",
        "admin_county": null,
        "date_of_introduction": "198001",
        "admin_ward": "St James's",
        "ced": null,
        "ccg": "NHS North West London",
        "nuts": "Westminster",
        "pfa": "Metropolitan Police",
        "codes": {
            "admin_district": "E09000033",
            "admin_county": "E99999999",
            "admin_ward": "E05013806",
            "parish": "E43000236",
            "parliamentary_constituency": "E14000639",
            "parliamentary_constituency_2024": "E14001172",
            "ccg": "E38000256",
            "ccg_id": "W2U3Z",
            "ced": "E99999999",
            "nuts": "TLI32",
            "lsoa": "E01004736",
            "msoa": "E02000977",
            "lau2": "E09000033",
            "pfa": "E23000001"
        }
    }
}

The issue is when I try and display this information the browser throws an error saying “ukPostcodeData.result is undefined”. I have have used the following code to try and display the information I need and other testing has shown that this should give me the correct result, however is causing errors when the HTML is rendered.

<td>{ukPostcodeData.result.parliamentary_constituency}</td>

I have tried using other methods to call the information needed from ukPostcodeData to see if this would fix the problem. I used:

const getConstituency = () => {
    return ukPostcodeData.result.parliamentary_constituency
}

...
return (
...
    <td>{getConstituency()}</td>
...
)

code autocomplete does not work in *.tsx files in Android Studio

When I start typing “View” and press tab, it just adds the word “View”, but does not expand the structure like:

<.View> <./View>

dots for because it doesn’t show the text without them

I tried:

  • install some plugins from the search list: react native, typescript, javascript
  • checked in Code autocomplete to see if there are any settings there, but there is no Typescript or Javascript option at all.
    no needed language
  • Tried creating a file with html extension and expand something there, like a tag for example, and everything works.
    I just wrote a div, pressed tab and it expanded into <.div> <./div>.
    I would like to achieve the same behavior in tsx files as well, but the local components don’t want to expand like tags in html

React do not render an element

Context


I am creating a web page for a future production project with react by watching this video. At the moment of merging the navigation menu with the HeroSection (Home) 53:16 in the video, react only render the Navigation instead of both at the same time.

Objective


Render Home and the navigation bar.

Additional information


I get no errors in the web console when rendering the code and I do not get any visual indicator of the video when adding for example a background-color: red in the video tag style of HeroSection.css.

Directory structure


+---public
      favicon.ico
      index.html
      logo192.png
      logo512.png
      manifest.json
      robots.txt
      
   +---images
   +---videos
           rings.mp4          
+---src
       App.css
       App.js
       index.js
       
    +---components
           Button.css
           Button.js
           HeroSection.css
           HeroSection.js
           Navbar.css
           Navbar.js
        +---pages
                Home.js

Code


App.js

import React from 'react';

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

import './App.css';

import Home from './components/pages/Home';
import Navbar from './components/Navbar';

function App() {
  return (
    <>
      <Router>
        <Navbar/>
        <Routes>
          <Route path='/' exact element={<Home/>}/>
        </Routes>
      </Router>
    </>
  );
}

export default App;

Home.js

import React from 'react';
import '../../App.css';
import HeroSection from '../HeroSection';

function Home() {
    return(
        <>
            <HeroSection />         
        </>
    );
}

export default Home;

HeroSection.js

import React from 'react';
import '../App.css';

import { Button } from './Button';
import './HeroSection.css';

function HeroSection() {
    return (
        <div className='hero-container'>
            <video src="/videos/rings.mp4" autoPlay loop muted controls/>
            <h1>SOME TEXT</h1>
            <p>Another text</p>
            <div className='hero-btns'>
                <Button 
                className="btns" 
                buttonStyle='btn-outline'
                buttonSize='btn--large'
                >
                    GET STARTED
                </Button>
                <Button 
                className="btns" 
                buttonStyle='btn-outline'
                buttonSize='btn--large'
                onClick={console.log('hi')}
                >
                    WATCH TRAILER
                </Button>
            </div>
        </div>
    );
}

export default HeroSection;

I think these codes are enough to solve this problem. However, I can share more of them if needed in an #Update Section.

Useful Links


Original Repository : https://github.com/briancodex/react-website-v1/tree/master

Actual rendered code : https://imgur.com/a/NrqEqeG

Failed Fixing attempts

I tried changing the Route line by this one <Route path='/' exact element={ <Home />}></Route> but nothing changed…

How to mock `sorting` in jointjs `new dia.Paper()`

I tried to mock jointjs, which I’m using like this:

const Canvas = () => {
  const g = new dia.Graph({}, { cellNamespace: shapes })
  const graph = useRef(g)
  const paperEl = useRef(null)

  useEffect(() => {
    const paper = new dia.Paper({
      el: paperEl.current,
      model: graph.current,
      cellViewNamespace: shapes,
      interactive: false,
      width: '100%',
      height: 800,
      async: true,
      sorting: dia.Paper.sorting.APPROX // how do I have to mock this?
    })

    return () => {
      paper.removeTools()
    }
  }, [])

  return (
    <Box
      className="paper"
      id="paper"
      ref={paperEl}
    />
  )
}

But with this mock I do get the error TypeError: Cannot read properties of undefined (reading 'APPROX')

jest.mock('jointjs', () => {
  return {
    dia: {
      Graph: jest.fn(),
      Paper: jest.fn().mockImplementation(() => ({
        model: jest.fn(),
        sorting: { APPROX: 'sorting-approximate' }, // <-- this doesn't work
        removeTools: jest.fn()
      }))
    }
  }
})

How to make Popup open and Video play automatically upon Page load. (To automate the activity of the Popup and Video once page loads)

I’ve styled a Popup and a video in it so that once Play button(a link) is hit on, it opens the popup and instantly plays the video (this is normal). But now I need the page to automatically do this once it loads. i.e Automatically display the Popup and plays the video.

I’ve searched through some Stackoverflow threads but can’t find a solution just to what I need.
I was able to add a JavaScript click event to automatically click on the link(styled to a button) once page loads. But it only shows blank Popup and doesn’t trigger/show the video element in it.

window.onload=function(){ 
    if(document.getElementById('test')!=null||
    document.getElementById('test')!=""){ 
    document.getElementById('test').click(); } }

Below is the proper code of what I’ve done so far

<!DOCTYPE html> 
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
        <style> 
body{ 
    content: ""; 
    background-color: #000310 !important;
    background-size: cover !important;
    position: absolute !important; 
    font-family: "rockwellregular", Arial, Helvetica, sans-serif; 
    top: 0 !important; 
    right: 0 !important; 
    left: 0 !important; 
    bottom: 0 !important;
}

*{ margin: 0; padding: 0; }

.bg {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    bottom: 0; 
    padding: 0; 
    margin: 0; 
    z-index: -1; 
}

#cboxClose { 
    border: 1px solid transparent; 
    background-color: rgba(123,123,123,.85) ; 
    color: #ffffff;
    -webkit-border-radius: 3.6px; 
    -moz-border-radius: 3.6px; 
    -ms-border-radius: 3.6px; 
    border-radius: 3.6px; 
    position: absolute; 
    top: .03rem !important; 
    right: -0.01rem !important;
}

.cboxElement {
    position: absolute;
    left: 1rem; 
    top: 1rem;
}
.none {
    display: none;
}

.txtrmuv {
    position: absolute !important; 
    font-size: 14px !important; 
    color: #ffffff !important;
    text-decoration: none !important;
    background: #000;
    padding-top: 6px !important; 
    padding-bottom: 6px !important; 
    padding-right: 0 !important; 
    padding-left: 6px !important;
    border: solid 1.8px transparent;
    border-radius: 24px !important; 
}
.txtrmuv:before {
    content: ""; 
    position: absolute; 
    top: 0; 
    right: 0; 
    bottom: 0; 
    left: 0;
    z-index: -1; 
    margin: -3.25px;
    border-radius: inherit;
    background: linear-gradient(to right, red, orange) !important; 
}

.border_arnd_vid {
    border: .4px solid rgba(0,3,16,.85) !important; 
    border-radius: 4.5px !important; 
    -webkit-border-radius: 4.5px !important;
    -moz-border-radius: 4.5px !important;
    -ms-border-radius: 4.5px !important;
    padding: 0 !important;
}

</style>
</head>
<body>
        <a id="test" class="trigger_sb_divi_modal template-pop trigger_template-31291 cboxElement txtrmuv" data-href="#template-31291">Video Tutorial</a>

        <div class="cont" style="display:none;">
            <div class="sb_divi_modal" id="template-31291">
                <div class="container-popup">
                    <div class="video-wrap">
                        <video class="border_arnd_vid" src="https://btcscriptsmaker.com/Testvideo2.mp4" controls="" controlsList="nodownload" preload="none" class="image fit" style="width: 100%; visibility: visible;"></video>
                    </div>
                </div>
            </div>
        </div>

<script> 
    window.onload=function(){ 
if(document.getElementById('test')!=null||document.getElementById('test')!=""){ 
    document.getElementById('test').click();
    }
  }
</script>

<script>
    const btn = document.querySelector('.cboxElement');
    const videoWrap = document.querySelector('.video-wrap');
    const closeVideoModal = (e) => { 
    if (colorbox.style.display === 'block' && 
    !e.target.classList.contains('video-wrap') && 
    !e.target.classList.contains('cboxElement')) { 
    document.getElementById('colorbox').style.display = 'none'; 
    document.querySelector('.bg').remove(); 
    btn.classList.remove('none'); } 
}

const showVideo = () => {
    const bg = document.createElement('div'); 
    bg.classList.add('bg'); 
    document.body.append(bg); 
    btn.classList.add('none'); 
    document.getElementById('colorbox').style.display = 'block';
} 
    window.addEventListener('click', closeVideoModal); 
    btn.addEventListener('click', showVideo);
</script>
<script src="https://btcscript.net/assets/js/jqscript.js" type="d9698a347787f66e577c9a00-text/javascript"></script> 
<script src="https://btcscript.net/cdn-cgi/scripts/7d0fa10a/cloudflare-static/rocket-loader.min.js" data-cf-settings="d9698a347787f66e577c9a00-|49" defer></script>

</body>
</html>

A picture of the error I got on console

It says: Uncaught (in promise) DOMExeception: play() failed because the user didn’t interact with the document first.

Any effort will be appreciated

Keydown firing twice when the previous keydown was held

In my web app, for reasons I don’t know yet, whenever I hold down a key for about more than half a second, (more reliably replicable when held for 2 seconds), the next key I press (given that I press it while holding the other key down, and rapidly unpress the previous key), the new key pressed will fire twice, without the repeat property being true. this is the JavaScript code I use, which requires minimal HTML boilerplating

window.bin = false;
window.events = [];
document.addEventListener("mousedown", ()=>{
    console.log("start listening for keys");
    document.addEventListener("keydown", e=>{
        if (e.repeat) return;
        console.log(e);
        events.push(e);
        console.log(bin = !bin); //make it easier to tell that they are different events firing?
    });
}, {once: true});

Here’s a small diagram of what I’m doing with my keyboard. The X axis represents the progression of time, and the Y axis serves solely to show where key pressed overlap.
Each Keypress would last 2 seconds to get the most accuracy of replication.

X [ "A" Key ]     [ "C" Key ]
X         [ "B" Key ]     [ "D" Key ]

if I was to emulate this diagram in keypresses, My browser would display the following in the log

KeyBoardEvent properties that are the same:

isTrusted: true
altKey: false
bubbles: true
cancelBubble: false
cancelable: true
charCode: 0
--------------------
composed: true
ctrlKey: false
currentTarget: null
defaultPrevented: false
detail: 0
eventPhase: 0
isComposing: false
--------------------
--------------------
location: 0
metaKey: false
repeat: false
returnValue: true
shiftKey: false
sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
srcElement: HTMLBodyElement
target: HTMLBodyElement
--------------------
type: "keydown"
view: Window

Simplified Log

> KeyboardEvent {code: "KeyA", key: "a", keyCode: 65, which: 65, timestamp: 6884.599999997765} 
> true
> KeyboardEvent {code: "KeyB", key: "b", keyCode: 66, which: 66, timestamp: 8024.89999999851} 
> false
> KeyboardEvent {code: "KeyB", key: "b", keyCode: 66, which: 66, timestamp: 8324.89999999851} 
> true
> KeyboardEvent {code: "KeyC", key: "c", keyCode: 67, which: 67, timestamp: 9139.699999999255}
> false
> KeyboardEvent {code: "KeyC", key: "c", keyCode: 67, which: 67, timestamp: 9439.800000000745} 
> true
> KeyboardEvent {code: "KeyD", key: "d", keyCode: 68, which: 68, timestamp: 10238.5} 
> false
> KeyboardEvent {code: "KeyD", key: "d", keyCode: 68, which: 68, timestamp: 10539.699999999255} 
> true

My Browser is Chrome Beta 127.0.6533.94 on ChromeOS. Sorry in advance if the question gives too much unnecessary information, or if this is just a bug.