Traversal with .closest() fails

I’m puzzled why thew second traversal with .closest seems to fail in this simple example:

 
        function testClosest(element) {
            let firstParentDiv = element.closest('div');
            console.log('First Parent Div ID:', firstParentDiv.id);

            let secondParentDiv = firstParentDiv.closest('div');
            console.log('Second Parent Div ID:', secondParentDiv ? secondParentDiv.id : 'None');
        }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Test for .closest() Method</title>
</head>

<body>

    <div id="grandparent">
        Grandparent
        <div id="parent">
            Parent
            <div id="child">
                Child
                <button onclick="testClosest(this)">Test Closest</button>
            </div>
        </div>
    </div>
    
</body>

</html>

I’m expecting the second console log to say “parent” but instead it logs “child” again.
Why is the second traversal attempt not working?

CORS Policy error in Webpage Replication Project

I recently dove into the coding world and I’m super excited about a project I’m working on – trying to replicate a webpage. However, I’ve hit a roadblock with the CORS policy. Any chance someone could lend a hand and guide me through this? Thanks a bunch!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Quote Generator</title>
</head>
<body>

    <div>
        <p>Random Quote:</p>
        <p><span class="text"></span></p>
        <p>Author: <small class="author"></small></p>
        <button onclick="getRandomQuote()">Get Random Quote</button>
    </div>

    <script>
        function getRandomQuote() {
            fetch('https://quotes.toscrape.com/random')
                .then(response => response.json())
                .then(data => {
                    document.querySelector('.text').textContent = data.quote;
                    document.querySelector('.author').textContent = data.author;
                })
                .catch(error => {
                    console.error('Error fetching random quote:', error);
                });
        }
        getRandomQuote();
    </script>

</body>
</html>

The login system does not work on PHP 8.1

The login system, which is written in PHP, does not work. Despite the fact that registration works. The login, in turn, does not work. When I click the “login” button, according to the logic of the written script, I should be redirected to the welcome page where the user name will be displayed. But instead I have an error.
The page is unavailable. The www.mydomain.com website cannot yet process this request.
HTTP ERROR 500

login system code

`

<?php
include 'db.php';
session_start();
if (isset($_POST['login'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$sql = "SELECT * FROM users WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_email'] = $user['email'];
header("Location: welcome.php");
} else {
$error_message = "Invalid email or password";
}
$stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - Creating a Login and Registration System in PHP 8.1 - LaravelTuts.com</title>
<!-- Add Bootstrap CSS -->
<link href="link"   crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card my-5" >
<div class="card-body">
<h1 class="text-center ">Creating a Login and Registration System in PHP 8.1</h1>
</div>
</div>
<h1 class="text-center my-5">Login</h1>
<?php if (isset($error_message)): ?>
<div class="alert alert-danger" role="alert">
<?= $error_message; ?>
</div>
<?php endif; ?>
<form action="login.php" method="post">
<div class="form-group mb-2">
<label for="email" class="mb-2">Email:</label>
<input type="email" name="email" id="email" class="form-control" required>
</div>
<div class="form-group mb-3">
<label for="password" class="mb-2">Password:</label>
<input type="password" name="password" id="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="login" value="Login" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<!-- Add Bootstrap JS and its dependencies -->
<script src="link to script"></script>
<script src="link to script"></script>
</body>
</html>`

register system

`

<?php
include 'db.php';
if (isset($_POST['register'])) {
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $email, $hashed_password);
$stmt->execute();
if ($stmt->affected_rows > 0) {
header("Location: login.php");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<!-- Add Bootstrap CSS -->
<link href="link">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card my-5" >
<div class="card-body">
<h1 class="text-center ">Creating a Login and Registration System in PHP 8.1</h1>
</div>
</div>
<h1 class="text-center my-5">Register</h1>
         
<form action="register.php" method="post">
<div class="form-group mb-2">
<label for="username" class="mb-2">Username:</label>
<input type="text" name="username" id="username" class="form-control" required>
</div>
<div class="form-group mb-2">
<label for="email" class="mb-2">Email:</label>
<input type="email" name="email" id="email" class="form-control" required>
</div>
<div class="form-group mb-3">
<label for="password" class="mb-2">Password:</label>
<input type="password" name="password" id="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="register" value="Register" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<!-- Add Bootstrap JS and its dependencies -->
<script src="link to script"></script>
<script src="link to script"></script>
</body>
</html>`

welcome page system

`

<?php
include 'db.php';
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
}
if (isset($_POST['logout'])) {
session_destroy();
header("Location: register.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard - Creating a Login and Registration System in PHP 8.1</title>
<!-- Add Bootstrap CSS -->
<link href="link">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card my-5" >
<div class="card-body">
<h1 class="text-center ">Creating a Login and Registration System in PHP 8.1</h1>
</div>
</div>
<h1 class="text-center my-5">Dashboard</h1>
<p class="text-center">Welcome, <strong><?= $_SESSION['user_email']; ?></strong></p>
<form action="dashboard.php" method="post" class="text-center">
<input type="submit" name="logout" value="Logout" class="btn btn-danger">
</form>
</div>
</div>
</div>
<!-- Add Bootstrap JS and its dependencies -->
<script src="link to sript"></script>
<script src="link to sript"></script>
</body>
</html>`

I tried the PPP version in Spanel from 8.1 to 7.6 but no changes. My database (fastmon4_login_system) and table (users) are built correctly since the registration system works. And new accounts are added to the list. It is the login system that does not work. The Java script also works. The submit button works. The problem is most likely in the php code.My table users in my database consists of

users:
1 id Primary int(11) AUTO_INCREMENT

2 username varchar(255) utf8mb4_general_ci

3 email Index varchar(255) utf8mb4_general_ci

4 password varchar(255) utf8mb4_general_ci

How to Connect to an MQTT Broker from a JavaScript Client (React) Without Exposing Credentials (username and password)

I am attempting to connect my React application to my Mosquitto MQTT broker securely without exposing my username and password, since anyone has access to the js code and could see the credentials.

The options I’ve considered so far are as follows:

Using mqtt.js to connect my client directly would expose my username and password. Therefore, I am contemplating building an API that returns my credentials if the user is authenticated (let’s say JWT). However, there’s a concern that if someone gains access to the user token, they’ll be able to retrieve the username and password, making this approach less secure.

Building an API that connects to the MQTT broker, saves the data in MongoDB, and later exposes endpoints to access the data. Although this is what I am currently working on, it seems fundamentally flawed as I may end up losing many advantageous features of MQTT. In this case, it might be worth considering abandoning MQTT altogether.

I was wondering if it is possible to add username and password in the backend and return the mqtt connection to the client, using the backend as some sort of middleware to add the missing information, only if the jwt is valid.

I am aware that I could use a custom plugin for MQTT to validate my JWT token, but I am not inclined towards this option due to the potential added complexity. Building and configuring the broker and the plugin might introduce additional sources of problems.

React Router Wrapped in a BottomNavigation not loading the new component

I can not for the life of me figure out how to load the DMO page from a BottomNavigation component. Going to "/dom" works perfectly. Clicking the buttons does not work at all. The initial "/" loads great. Thoughts? Suggestions?

import * as React from 'react';
import Box from '@mui/material/Box';
import BottomNavigation from '@mui/material/BottomNavigation';
import BottomNavigationAction from '@mui/material/BottomNavigationAction';
import AccountTreeIcon from '@mui/icons-material/AccountTree';
import DatasetLinkedIcon from '@mui/icons-material/DatasetLinked';
import LogoutIcon from '@mui/icons-material/Logout';
import './navigation.css'
import {createBrowserRouter, Link, RouterProvider} from 'react-router-dom';
import PmoTable from "../PmoTable/PmoTable";
import DMO from "../DMO/DMO";

export default function Navigation() {
  const [value, setValue] = React.useState(0);
  const router = createBrowserRouter([
    {
      path: "/",
      element: <PmoTable />,
    },
    {
      path: "dmo",
      element: <DMO />,
    }
  ]);

  return (
    <Box className="navBar">
      <RouterProvider router={router} />
      <BottomNavigation
        showLabels
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
      >
        <BottomNavigationAction label="PMO" icon={<AccountTreeIcon />} >
          <Link to='/'></Link>
        </BottomNavigationAction>
        <BottomNavigationAction label="DMO" icon={<DatasetLinkedIcon />} >
          <Link to='/dmo'></Link>
        </BottomNavigationAction>
        <BottomNavigationAction label="Logout" icon={<LogoutIcon />} >
          <Link to='/logout'></Link>
        </BottomNavigationAction>
      </BottomNavigation>
    </Box>
  );
}

How to open a new html file inside JS with webpack

I’m trying to add a button that redirects to a new page called “app.html” which is part of my project, but I haven’t been able to do it since no matter what I do I always get something unexpected.
I read that a tags are quite weirs when using webpack, so I added the necessary lines (according to what I’ve seen online) to the webpack config file like this:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    mode: "development",
    entry: {
        home: "./src/index.js",
        app: "./src/pages/app.js",
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].bundle.js",
        clean: true,
    },
    devServer: {
        static: {
            directory: path.resolve(__dirname, "dist"),
        },
        port: 3000,
        open: true,
        hot: true,
        compress: true,
        historyApiFallback: true,
    },
    module: {
        rules: [
            {
                test: /.(png|jpe?g|gif)$/i,
                use: [
                    {
                        loader: "file-loader",
                    },
                ],
            },
            {
                test: /.css$/i,
                include: path.resolve(__dirname, "src"),
                use: ["style-loader", "css-loader", "postcss-loader"],
            },
            {
                test: /.svg$/,
                use: [
                    {
                        loader: "svg-url-loader",
                        options: {
                            limit: 10000,
                        },
                    },
                ],
            },
            {
                test: /.html$/i,
                loader: "html-loader",
                options: {
                    sources: {
                        list: [
                            "...",
                            {
                                tag: "a",
                                attribute: "href",
                                type: "src",
                            },
                        ],
                    },
                },
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: "index.html",
            template: "src/views/index.html",
            chunks: ["home"],
        }),
        new HtmlWebpackPlugin({
            filename: "app.html",
            template: "src/views/app.html",
            chunks: ["app"],
        }),
    ],
};

I added the options arguments to include a tags correctly. However, in my home.js file I imported the html file I want to redirect the user to:

import appPage from "html-loader!../views/app.html";

And then I created a button on my index.html by injecting it with vanilla JS such as this:

    const startButton = document.createElement("a");
    startButton.id = "start-button";
    startButton.innerText = "Get Started";
    startButton.href = loginPage;

However, when clicking on the button I get to a new page about:blank#blocked and not to the page I’m actually referencing on the href tag. By inspecting the website I can see the a tag has the following content:

<a id="start-button" href="// Module
var code = &quot;<!DOCTYPE html>rn<html lang=&quot;en&quot;>rnt<head>rntt<meta charset=&quot;UTF-8&quot; />rntt<meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; />rntt<title>Todoers</title>rnt</head>rnt<body>rntt<h1 class=&quot;text-7xl font-bold&quot;>HELLO TODOERS, LOGIN HERE</h1>rnt</body>rn</html>rn&quot;;
// Exports
export default code;">Get Started</a>

Which is in fact the raw content of the app.html file itself. I’m not sure it should be doing that, I would guess the correct way would be to have a new app.html file inside the src folder (which is being created by webpack correctly) and then reference that file, since I will be using different bundles.

I’m extremely confused by this, any help would be appreciated. I’ll leave a link to the GitHub repo as well, which has the latest build of the project.

Javascript Discord Bot not responding to interactions

I’m following this really simple Discord Bot tutorial using Javascript, and I’m running into an issue. The bot is able to login and all that, but when I actually use the slash command, it doesn’t respond and CMD says:
ReferenceError: interaction is not defined at Client.handleInteraction (file:///C:/Program%20Files/discord-bot/bot.js:18:5)

I have the following code for my main bot file named bot.js:

`import { Client, Events, GatewayIntentBits } from 'discord.js';
import { config } from 'dotenv';
import * as bos from './commands/sticks.js';


config();

const client = new Client({
    intents: [GatewayIntentBits.Guilds],
});

function readyDiscord() {
    console.log("Hello " + client.user.tag);
}

async function handleInteraction() {
    if (!interaction.isCommand()) return;
    if (interaction.commandName === 'sticks') {
        await bos.execute(interaction);
    }
}

client.once(Events.ClientReady, readyDiscord);

client.login(process.env.TOKEN);

client.on(Events.InteractionCreate, handleInteraction);`

my actual command file named sticks.js:

import { SlashCommandBuilder } from 'discord.js';

// Command Builder export
export const data = new SlashCommandBuilder()
    .setName('sticks')
    .setDescription('Fun bundle of sticks!');

// Execute function export
export async function execute(interaction) {
    await interaction.reply('Sticks');
}`

the deploy commands file:

`// Importing modules using ES6 syntax
import { REST, Routes } from 'discord.js';
import { config } from 'dotenv';
import fs from 'node:fs';

config(); // Using dotenv config function directly

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter((file) => file.endsWith('.js'));

// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
  const command = await import(`./commands/${file}`); // Using dynamic import
  if ('data' in command && 'execute' in command) {
    commands.push(command.data.toJSON());
  } else {
    console.log(`[WARNING] The command ${file} is missing a required "data" or "execute"   property.`);
  }
}

// Construct and prepare an insance of the REST module
const rest = new REST().setToken(process.env.TOKEN);

// and deploy your commands!
(async () => {
  try {
    console.log(`Started refreshing ${commands.length} application (/) commands.`);

    // The put method is used to fully refresh all commands in the guild with the current set
    const data = await rest.put(Routes.applicationGuildCommands(process.env.CLIENTID,   process.env.SERVERID), {
      body: commands,
    });

    console.log(`Successfully reloaded ${data.length} application (/) commands.`);
  } catch (error) {
    // And of course, make sure you catch and log any errors!
    console.error(error);
  }
})();`

My .env file is also setup correctly with the right SERVERID, CLIENTID, and TOKEN.
I feel like I’m missing something very obvious, but I can’t pinpoint it.

I tried renaming the interaction names, reviewing my video reference. It’s supposed to respond to a simple slash command of ‘/sticks’, but when I do that it says “The application did not respond”. I made sure to deploy the commands and log the bot in.

React Native error: Could not find com.facebook.react:react-android:

I’m getting this error when after installing react-native-worklets :

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':react-native-worklets-core:compileDebugAidl'.
> Could not resolve all task dependencies for configuration ':react-native-worklets-core:debugCompileClasspath'.
   > Could not find com.facebook.react:react-android:.
     Required by:
         project :react-native-worklets-core

My package version:

{
  "name": "gestionart",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-reanimated": "2.10.0",
    "react-native-vision-camera": "^2.15.2",
    "react-native-worklets-core": "^0.2.4",
    "vision-camera-mrz-scanner": "^0.3.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

Making a counter with a closure in Elixir

I’m learning Elixir and I just got to the part about closures. When a language has closures, the first thing I usually do is try to make the closure algorithm. In JavaScript it looks something like this:

let counter = function() {
    let count = 0;
    return function() {
        count += 1;
        return count;
    };
}();

Then, each time that counter is called, it will return a new number in sequence.

counter(); //  returns 1
counter(); //  returns 2
counter(); //  returns 3
counter(); //  etc.

Is it possible to make this in Elixir? The main problem seems to be that count would be immutable in Elixir. I could make it a one-element list, but that sounds like a Bad Idea™. What would be the Elixir way of dealing with this purely hypothetical situation?

How do I create bold text in email using Google App Script?

I am using the submission of a Google Form to fill a Google Sheet. On the form submission an email will be generated to the recipient addressed in the form via the Google App Script in the Google Sheet. In this email, I would like to make the title/positions “Director of Bands and Choirs’ and “Honors Choir Coordinator” listed in my email signature bold. If I can also make my name appear larger in the signature, that would be nice as well.

function afterFormSubmit(e) {

const info = e.namedValues;
const pdfFile = createPDF(info);
const entryRow = e.range.getRow();
const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
ws.getRange(entryRow, 5).setValue(pdfFile.getUrl());
ws.getRange(entryRow, 6).setValue(pdfFile.getName());

sendEmail(e.namedValues['Email'][0],pdfFile);

}


function sendEmail(email,pdfFile){


GmailApp.sendEmail(email, "Honors Choir", "Esteemed Colleague, nnAttached to this email is a                 confirmation of registration & receipt of payment for the Honors Choir. nnAdditionally, it appears that music for the concert is on backorder. I will share a folder with scans of the music with you soon. However, please make sure to support our fellow musicians by ordering the originals. nnSincerely, nMy Name n<b>Director of Bands and Choirs</b> nA Michigan High School | School Address | City, State ZIP CODEnWebsite.com | Facebook: Account nnHonors Choir Coordinator nwww.Website.org | Facebook: Account",    {
attachments: [pdfFile],
name: 'Honors Choir Coordinator'
});

}

How to handle multiple images to download using Next.js?

I have a route called /photos, which supports pagination through a ‘page’ query parameter and allows me to specify the number of photos per page using ‘pageSize’. It returns an array of photos and the total count of photos available.

This is my api route
/photos?cameraId=580&start=2023-10-29&end=2023-10-30&beginTime=18:00&endTime=19:00&Page=1&PageSize=10
This is my return object
{
    "photos": [
        {  "urlPreview": "https://example.com/random-preview-url"  }
        ...
    ],
    "total": 239
}

Now, I need to implement a button on my page that, when clicked, will start downloading these photos. The total number of photos is approximately 12K, which obviously takes some time and processing.

I’ve been advised to use localStorage to save the photos incrementally and then zip them all for the user to download.

However, I have no idea how to implement this as I’ve never done anything like this before. Can someone please guide me on how to proceed?

I was trying to download using my downloadMassivePhotos function like this

import JSZip from 'jszip';
import { saveAs } from 'file-saver';

export const downloadMassivePhotos = async (
  cameraId,
  start,
  end,
  beginTime,
  endTime,
) => {
  const zip = new JSZip();
  const maxConcurrentDownloads = 20;
  let activeDownloads = 0;

  try {
    const { photos } = await fetchAPI({
      path: 'photos',
      query: { cameraId, start, end, beginTime, endTime },
    });

    for (const photo of photos) {
      while (activeDownloads >= maxConcurrentDownloads) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }

      activeDownloads++;

      fetchAndZipPhoto(photo, zip)
        .catch((error) => {
          console.error(`Error downloading photo ${photo.id}:`, error);
        })
        .finally(() => {
          activeDownloads--;
        });
    }

    while (activeDownloads > 0) {
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }

    const content = await zip.generateAsync({ type: 'blob' });
    saveAs(content, 'photos.zip');
  } catch (error) {
    console.error(error);
  }
};

const fetchAndZipPhoto = async (photo, zip) => {
  const { urlImage, id } = photo;
  const response = await fetch(urlImage);
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  const blob = await response.blob();
  zip.file(`${id}.jpg`, blob, { binary: true });
};

And this is my fetch method

export const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_HOST,
});

export const fetchAPI = async <T>({ path, query, context }: FetchAPI) => {
  const session = await getSession(context);

  const { data, status } = await api.get<T>(`/${path}`, {
    headers: { Authorization: `Bearer ${session?.token}` },
    params: query,
  });

  if (!data && status !== 200) {
    throw new Error(`API call to ${path} failed.`);
  }

  return data;
};

cant get my dialog element to show from calling a function

addConfirm is a dialog element which is a confirmation modal that is supposed to pop up after a successful api call in this function.

async function handleAddProduct(item: typeof newItem) {
    setShopLoading(true);

    try {
      const response = await privateReq.post("/items", item);
      addConfirm.showModal(); 
      setShopItems(response.data?.updatedList);
      addedId.current = response.data?.added?.item_id;
    } catch (error) {
        console.error(error):
    } finally {
      setShopLoading(false);
    }
  }

I get this error when i run this function

Uncaught DOMException: HTMLDialogElement.showModal: Dialog element is not connected

I tried to just test it without the api call and it works as intended

async function handleAddProduct(item: typeof newItem) {
 
addConfirm.showModal(); 
 return    //exits the function to test if modal is working

    setShopLoading(true);
    try {
      const response = await privateReq.post("/items", item);
            setShopItems(response.data?.updatedList);
      addedId.current = response.data?.added?.item_id;
    } catch (error) {
        console.error(error):
    } finally {
      setShopLoading(false);
    }
  }

I also tried to bind the modal to a state and useeffect to make sure its not null when showModal() is called but it didnt change anything

Adjusting Openlayers Panning Speed

How can I adjust the pan speed in Openlayers?

When I drag the map around, there is about a 1 second slow-down animation before the map stops and the content is updated. I want to reduce this so that the time it takes to load the content after the user lets go of the map is faster.

I have not found anything related to solving this problem yet. All documentation on “animation” deals with automatically panning to a coordinate on the map – which is not what I am trying to do.

React Native MapView Crashes

React Native MapView crashes when i build android apk file, however it is smoothly running on simulator, below is my map view code: DeliveryScreen.js

import React, { useState, useEffect, useMemo } from 'react';
import { View, Text, SafeAreaView, TouchableOpacity} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import MapView, { Marker, Polyline, PROVIDER_GOOGLE } from 'react-native-maps';
import { useNavigation } from '@react-navigation/native';
import { HomeIcon } from 'react-native-heroicons/solid';
import { selectRestaurant } from '../features/restaurantSlice';
import { resetBasket } from '../features/basketSlice';



const DeliveryScreen = () => {
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const restaurant = useSelector(selectRestaurant);
  const [distance, setDistance] = useState('Calculating...');

  const homeLocation = { latitude: 52.50768847543942, longitude: 13.294998226071066 };

  const clearBasketAndReturnHome = () => {
    dispatch(resetBasket());
    navigation.navigate('Home');
  };

  const calculatedDistance = useMemo(() => {

      const earthRadius = 6371;
      const { lat, long } = restaurant;
      const { latitude, longitude } = homeLocation;

      const dLat = (latitude - lat) * (Math.PI / 180);
      const dLon = (longitude - long) * (Math.PI / 180);

      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat * (Math.PI / 180)) * Math.cos(latitude * (Math.PI / 180)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);

      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return (earthRadius * c).toFixed(2) + ' km';
  }, [restaurant, homeLocation]);

  useEffect(() => {
    setDistance(calculatedDistance);
  }, [calculatedDistance]);

  return (
    <View style={{ flex: 1, backgroundColor: '#00CCBB' }}>
      <MapView
        provider={PROVIDER_GOOGLE}
        
        initialRegion={{
          latitude: restaurant.lat,
          longitude: restaurant.long,
          latitudeDelta: 0.05,
          longitudeDelta: 0.05,
        }}
        style={{ flex: 1, marginTop: -10, zIndex: 0 }}
      >
        <Polyline
          coordinates={[
            { latitude: restaurant.lat, longitude: restaurant.long },
            homeLocation,
          ]}
          strokeColor="#ee5253"
          strokeWidth={6}
        />
        <Marker coordinate={homeLocation} pinColor="#ee5253" />
        <Marker
          coordinate={{ latitude: restaurant.lat, longitude: restaurant.long }}
          title={restaurant.title}
          description={restaurant.short_description}
        />
      </MapView>

      <SafeAreaView style={{ backgroundColor: 'white', flexDirection: 'row', alignItems: 'center', paddingHorizontal: 10, height: 130 }}>
        <View>
          <Text style={{ fontSize: 14, color: 'gray', paddingLeft: 5 }}>Distance to Restaurant</Text>
          <Text style={{ fontSize: 18, fontWeight: 'bold', paddingLeft: 5 }}>{distance}</Text>
        </View>
        <TouchableOpacity onPress={clearBasketAndReturnHome} style={{ right: -45, padding: 12, backgroundColor: '#34D399', borderRadius: 999, zIndex: 50 }}>
          <HomeIcon size={20} color='#FFFFFF' />
        </TouchableOpacity>
      </SafeAreaView>
    </View>
  );
};

export default React.memo(DeliveryScreen);

The code runs smoothly on simulator however when im building an APK file then when it reaches the map, the app crashes and quit.

Please any help would be appreciated.

Auth0 create method running getUser instead

I’m using my own store for my application auth while using Auth0. when I try to sign up instead of running the Create Database Action Scripts it runs the one for Get User. Do you have any suggestions on why?

// create method
function login(email, password, callback) {
 const request = require('request');

 request.get({
   url: configuration.url+'profile',
   auth: {
     username: email,
     password: password
   }
   //for more options check:
   //https://github.com/mikeal/request#requestoptions-callback
 }, function(err, response, body) {
   if (err) return callback(err);
   if (response.statusCode === 401) return callback();
   const user = JSON.parse(body);

   callback(null, {
     user_id: user.user_id.toString(),
     nickname: user.nickname,
     email: user.email
   });
 });
}
//get user method
function loginByEmail(email, callback) {
  const request = require('request');

  request.get({
    url: configuration.url+'users-by-email/' + email
    //for more options check:
    //https://github.com/mikeal/request#requestoptions-callback
  }, function(err, response, body) {
    if (err) return callback(err);

    const user = JSON.parse(body);

    callback(null, {
      user_id: user.user_id.toString(),
      nickname: user.nickname,
      email: user.email
    });
  });
}

I’m sure it’s running the wrong code because it’s reaching out to the endpoint to get a user by email.
My idea is that the get user method checks if the account exists before creating, but I don’t know what to respond with.