react-dom.development.js:86 Warning: validateDOMNesting(…): cannot appear as a descendant of

I can not understand why this warning is appearing
react-dom.development.js:86 Warning: validateDOMNesting(…): cannot appear as a descendant of .

This in my code here.

import React from 'react'
import { NavLink } from 'react-router-dom'
import { Container, Nav, Navbar } from 'react-bootstrap';



const Navigation = () => {
  return (
    <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
      <Container>
        <Navbar.Brand href="/"><NavLink to="/" className="nav-link3">Restaurant-App</NavLink></Navbar.Brand>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
          <Nav className="me-auto">
            <Nav.Link href="#features" ><NavLink to="/" className="nav-link3">Home</NavLink></Nav.Link>
            <Nav.Link href="#pricing" ><NavLink to="/list" className="nav-link3">List</NavLink></Nav.Link>
            <Nav.Link href="#features"><NavLink to="/create" className="nav-link3">Create</NavLink></Nav.Link>
            <Nav.Link href="#pricing"><NavLink to="/search" className="nav-link3">Search</NavLink></Nav.Link>
            <Nav.Link href="#pricing" ><NavLink to="/update" className="nav-link3">Update</NavLink></Nav.Link>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>

  )

}

export default Navigation

I used react-router-dom”: “^6.6.2

How to open datepicker on button click jquery

I am working on Jquery,Right now i am getting “datepicker” on “input type text”,but i want to display that datepicker on button click,how can i do this ? Here is my current code

<head>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Initialize the datepicker and display a button panel underneath the calendar.</title>
</head>
<body>
<p>Pick a date:</p>   
<p><input type="text" id="datepicker1" /></p> 
<button id="bt">Date</button>
</body>


<script>
 $('#bt').click(function(){
        $( "#datepicker1" ).datepicker({
    showButtonPanel: true
});
});
</script>

Javascript code within tag being rendered in the page

I am fairly new to the js and the referencing of the script. I have a particular js code in my partial view. The actual code is:

<script>

        var bID = @businessIDScript;
        var gID = @groupIDScript;
        var dID = @departmentIDScript;
        var aID = @areaIDScript;


        if (!(aID > 0)) {
            $("#createIdlerButton").attr("disabled", "disabled");
            $("#importIdlerButton").attr("disabled", "disabled");
        }

        if (@sapEnabled == true) {
            $("#sapIdlerReport").show();
            $("#sapIdlerReportAnchor").removeAttr('onClick');
            $("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
        } else {
            $("#sapIdlerReport").hide();
        }
 

</script>

complete razor view page is:

@using PDS.Domain.EF6.Resources.Web
@using Kendo.Mvc.UI
@using PDS.Web.Areas.PlannedInspections.Models;
@using PDS.Web.Utils;
@{
    var sapEnabled = ViewBag.SAPEnabled.ToString().ToLower();
    var isLaidOutHide = (string)ViewData["isLaidOutHide"];
    var EnforceUserDropDown = (string)ViewData["EnforceUserDropDown"].ToString().ToLower();
    var CurrentLevelIsDashboard = false;
    bool.TryParse(ViewData["CurrentLevelIsDashboard"].ToString(), out CurrentLevelIsDashboard);

    var WorkOrderDashboardParameters = ViewData["WorkOrderDashboardParameters"] != null ?
    (WorkOrderDashboardParameters)ViewData["WorkOrderDashboardParameters"] : null;

    var importDataName = ViewData["importDataName"]?.ToString() ?? "";
    var importTemplateUrl = ViewData["importTemplateUrl"]?.ToString() ?? "";
    var importActionUrl = ViewData["importActionUrl"]?.ToString() ?? "";
    var areaId = ViewData["areaId"]?.ToString().Trim() ?? "";

    var areaIDScript = string.IsNullOrEmpty(areaId) ? "0" : areaId;
    var breadcrumbTitle = ViewData["breadcrumbTitle"]?.ToString().Trim() ?? "";

    var areaIdStr = ViewData["areaId"]?.ToString().Trim() ?? null;
    var departmentIdStr = ViewData["departmentId"]?.ToString().Trim() ?? null;
    var groupIdStr = ViewData["groupId"]?.ToString().Trim() ?? null;
    var businessIdStr = ViewData["businessId"]?.ToString().Trim() ?? null;

    var businessId = "";
    if (!string.IsNullOrEmpty(businessIdStr))
    {
        businessId = businessIdStr;
    }
    else
    {
        using (var context = PDS.Domain.EF6.EF.CcMSEntitiesv6.CreateForUser(User))
        {
            if (!string.IsNullOrEmpty(groupIdStr))
            {
                var id = int.Parse(groupIdStr);
                businessId = context.vwAreas.FirstOrDefault(x => x.GroupID == id)?.BusinessID.ToString() ?? "";
            }
            else if (!string.IsNullOrEmpty(departmentIdStr))
            {
                var id = int.Parse(departmentIdStr);
                businessId = context.vwAreas.FirstOrDefault(x => x.DepartmentID == id)?.BusinessID.ToString() ?? "";
            }
            else if (!string.IsNullOrEmpty(areaIdStr))
            {
                var id = int.Parse(areaIdStr);
                businessId = context.vwAreas.FirstOrDefault(x => x.AreaID == id)?.BusinessID.ToString() ?? "";
            }
        }
    }
    var businessIDScript = string.IsNullOrEmpty(businessId) ? "0" : businessId;
    var groupIDScript = string.IsNullOrEmpty(groupIdStr) ? "0" : groupIdStr;
    var departmentIDScript = string.IsNullOrEmpty(departmentIdStr) ? "0" : departmentIdStr;
}

<div id="idler-grid-toolbar" class="toolbarGridContainer">

    <div class="pull-left">
        @(Html.Kendo().DropDownList()
                                        .Name("GridFilter")
                                        .HtmlAttributes(new { data_column = "IsAtRisk" })
                                        .Items(items =>
                                        {
                                            items.Add().Text(IdlerManagement.IdlerTag_Dropdown_HideReplaced).Value("active");
                                            items.Add().Text(General.All).Value("all");
                                            items.Add().Text(IdlerManagement.IdlerTag_Dropdown_AtRisk).Value("atrisk");

                                        })
                                        .Events(ev => ev.Change("PDS.IdlerManagement.activeIdlerDashboardFilterChanged"))
        )
        @(Html.Kendo().DropDownList()
                                        .Name("IdlerGridFilter")
                                        .HtmlAttributes(new { data_column = "Idler" })
                                        .Items(items =>
                                        {
                                            items.Add().Text(IdlerManagement.Idlers).Value("true");
                                            items.Add().Text(IdlerManagement.Structures).Value("false");
                                            items.Add().Text(General.All).Value("all");
                                        })
                                        .Events(ev => ev.Change("PDS.IdlerManagement.activeIdlerDashboardFilterChanged2"))
        )
        @if (!CurrentLevelIsDashboard)
        {
            <span class="pull-right">
                <button type="button" id="schematicsButton" class="btn btn-default" title='@IdlerManagement.Schematics_Button' onclick="PDS.IdlerManagement.editSchematic(this, '@areaId')">
                    @IdlerManagement.Schematics_Button
                </button>
            </span>
        }
        @if (User.IsInRole("Power User") || User.IsInRole("Business Administrator") || User.IsInRole("System Administrator"))
        {
            <div class="pull-right">
                <div class="dropdown shutdown-planner-dropdown">
                    <button type="button" id="shutdownPlannerTags" class="btn btn-default dropdown-toggle" title='@IdlerManagement.ShutdownPlanner_Button' data-toggle="dropdown">
                        @IdlerManagement.ShutdownPlanner_Button
                        <span role="button" unselectable="on" class="k-select" aria-label="select">
                            <span class="k-icon k-i-arrow-60-down"></span>
                        </span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-right" style="transform:translate3d(0px, 51px, 0px); overflow-y:auto">
                        <li>
                            <a href="#" class="addShutdown" onclick="PDS.IdlerManagement.shutdownPlannerAdd(this, '@businessId', '@breadcrumbTitle', '@User.Identity.Name')" id="shutdownPlannerTags">@IdlerManagement.ShutdownPlanner_Button_Add</a>
                        </li>
                        <li>
                            <a href="#" class="removeShutdown" onclick="PDS.IdlerManagement.shutdownPlannerRemove(this, '@User.Identity.Name')" id="shutdownPlannerTags">@IdlerManagement.ShutdownPlanner_Button_Remove</a>
                        </li>
                    </ul>
                </div>
            </div>
            @Html.Partial("_IdlerShutdownPlannerTemplate")
        }

        @if (!User.IsInRole("Read Only User"))
        {
            <button class="btn btn-default " onclick="PDS.IdlerManagement.closeOutIdlerTags(this, @EnforceUserDropDown, '@User.Identity.Name')" disabled="disabled" id="closeOutIdlerTags">@IdlerManagement.IdlerTag_Button_CloseOut</button>
            <button class="btn btn-default  @isLaidOutHide" onclick="PDS.IdlerManagement.laidOutIdlerTags(this, @EnforceUserDropDown, '@User.Identity.Name')" disabled="disabled" id="laidOutIdlerTags">@IdlerManagement.IdlerTag_Button_LaidOut</button>
        }
    </div>
    @if (WorkOrderDashboardParameters != null)
    {
        <span class="pull-right">

            <button type="button" data-role="close" id="viewAsset" class="btn btn-default" title="@General.Close" onclick="PDS.Common.UrlHistory.navigateBack()">
                <i class="fa fa-times"></i>
            </button>

        </span>
    }
    <span class="pull-right">
        @Html.Partial("_QuickReport", new ViewDataDictionary() { { "groupName", "Idler Management" } })
    </span>

    @Html.Partial("_ImportExportButtons", new ViewDataDictionary() { { "DownloadTemplateUrl", $"/GlobalImportExport/ImportWizard/DownloadImportTemplateByEntity?entityName=IdlerTag" }, { "EntityName", "IdlerTag" } })

    @if (!User.IsInRole("Read Only User"))
    {
        if (!CurrentLevelIsDashboard)
        {
            <div class="pull-right">
                <div class="dropdown create-idlerstructure-button-dropdown">
                    <button type="button" id="createIdlerButton" class="btn btn-default dropdown-toggle" title="@IdlerManagement.IdlerTag_Tooltip_CreateRecord" data-toggle="dropdown"><i class="fa fa-plus"></i></button>
                    <ul class="dropdown-menu dropdown-menu-right">
                        <li>
                            <a href="#" class="addIdler-Idler" onclick="PDS.IdlerManagement.createIdlerTag(this, true, '@areaId', @Html.Raw(WorkOrderDashboardParameters != null && WorkOrderDashboardParameters.workOrderTaskId.HasValue ? WorkOrderDashboardParameters.workOrderTaskId.ToString() : "null"))" id="laidOutIdlerTags">@IdlerManagement.IdlerTag_Button_CreateIdler</a>
                        </li>
                        <li>
                            <a href="#" class="addIdler-structure" onclick="PDS.IdlerManagement.createIdlerTag(this, false, '@areaId', @Html.Raw(WorkOrderDashboardParameters != null && WorkOrderDashboardParameters.workOrderTaskId.HasValue ? WorkOrderDashboardParameters.workOrderTaskId.ToString() : "null"))" id="laidOutIdlerTags">@IdlerManagement.IdlerTag_Button_CreateStructure</a>
                        </li>
                    </ul>
                </div>
            </div>
        }
    }


</div>

@Html.Partial("_ImportTemplate", new ViewDataDictionary() { { "importTemplateUrl", importTemplateUrl }, { "importActionUrl", importActionUrl } })

<script>

        var bID = @businessIDScript;
        var gID = @groupIDScript;
        var dID = @departmentIDScript;
        var aID = @areaIDScript;


        if (!(aID > 0)) {
            $("#createIdlerButton").attr("disabled", "disabled");
            $("#importIdlerButton").attr("disabled", "disabled");
        }

        if (@sapEnabled == true) {
            $("#sapIdlerReport").show();
            $("#sapIdlerReportAnchor").removeAttr('onClick');
            $("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
        } else {
            $("#sapIdlerReport").hide();
        }
 

</script>

The display looks like this: As you can see in the image below some of the js code is being rendered in the main page. I am having hard time fixing this issue.
Rendering of js in page

Note: There is no issue with the functionality of the code it works perfectly fine. Even tried doing console.log(“Hello World”). Throws the same dark half baked js in the page. Any help would be appreciated.
Thank you in advance.

What i have tried:
Initially, I thought this issue was due to some missing tags and closure in html tags but i fixed those issues and resolved up the console errors and warnings that i was getting for those tags. Also, i found out that “display none” on the script tag fixed that issue but my senior won’t allow it saying its not the solution just a hack. I don’t have a clue what is causing this issue because there are no warning nor any errors in VS. also i tried doing document.Ready function for this script but that failed miserably as well. Now i am out of depth and have no idea what is causing this error. Another solution i discovered was if i move this whole script inside a new <div> tag, it resolves the issue.

Expectation:
–> The js should not be rendered in the page.

Warning: Undefined variable $name in while attempting to edit mysql data with php [duplicate]

I am new to PHP and MySQL query. I am currently completing my course project, and am stucked in the process of editing data from MYSQL database, through PHP programming. HTML and CSS were used to build a webpage as well. My target is: In any rows that have the ‘name’and ‘matric_id’ elements empty, that is the row I’ll be editing and that are the 2 elements I’ll update into the database.

Below is my source code.
(Also, this is my first question posted on Stack Overflow, I apologise in advanced if there are certain things in the way I asked that is not right here.)

<? php
    session_start();
    require'connectDB.php';
    $id = "";
    $RFID_Value = "";
    $time_stamp = "";
    $name = "";
    $matric_id = ""; 
    $fp_value = "";

    $errormsg = "";
    $successmsg = "";

    if ($_SERVER['REQUEST_METHOD']=='GET')
    {
        //GET method: show the data of the student
        //1.check if id of std received
        if (!isset($_GET["id"]))
        {
            header("location: /LOC/first.php")
            exit;
        }
        require'connectDB.php';
        $id = $_GET["id"];
        //read the row of the selected student
        $sql = "SELECT * FROM info WHERE id=$id";
        $result = $conn->query($sql);
        $row = $result->fetch_assoc();

        if (!$row)
        {
            header("location: /LOC/first.php");
            exit;
        }
       
        $id = $row["id"];
        $RFID_Value = $row["RFID_Value"];
        $time_stamp = $row["time_stamp"];
        $name = $row["name"];
        $matric_id = $row["matric_id"];
        $fp_value = $row["fp_value"];
    }
    else
    {
        //POST method: Update the data of the student
        $id = $_POST["id"];
        $RFID_Value = $_POST["RFID_Value"];
        $time_stamp = $_POST["time_stamp"];
        $name = $_POST["name"];
        $matric_id = $_POST["matric_id"];
        $fp_value =  $_POST["fp_value"];
        //read data of the file?
        do
        {
            if(empty($id) || empty($RFID_Value) || empty($time_stamp) || empty($name) || empty($matric_id) || empty($fp_value))
            {
                $errormsg="All fields are required";
                break;
            }
            
            $sql = "UPDATE info". 
                   "SET name='$name', matric_id='$matric_id' "
                   "WHERE id=$id";

            $result = $conn->query($sql);

            if(!$result)
            {
                $errormsg="Invalid query: " . $conn->error;
                break;
            }

            $successmsg = "Student info updated!";

            header("location: /LOC/first.php");
            exit;
        }
        while(false);
    }
?>

<!DOCTYPE html>
<html>
<head>
    <title>COURSEWORK</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
      <link rel='stylesheet' type='text/css' href="css/bootstrap.css"/>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
      <link rel="stylesheet" type="text/css" href="css/header.css"/>
    

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>

    <script>
      $(window).on("load resize ", function() {
        var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width();
        $('.tbl-header').css({'padding-right':scrollWidth});
    }).resize();
    </script>
</head>

<body>
<main>
    <h2> New Student</h2>

    <?php
        if (!empty($errormsg))
        {
            echo "
            <div class='alert alert-warning alert-dismissible fade show' role='alert'>
                <strong> $errormsg</strong>
                <button type= 'button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'> </button>
            </div>
            ";
        }
    ?>

    <form method="post">
        <input type="hidden" name="id" value="<?php echo $id; ?>">
        <div>
        <label> name </label>
            <input type="text" class="form-control" name="name" value="<?php echo $name; ?>">
        </div>  

        <div>
        <label> matric_id </label>
            <input type="text" class="form-control" name="matric_id" value="<?php echo $matric_id; ?>">
        </div>  

        <div>
        <label> fp_value </label>
            <input type="text" class="form-control" name="fp_value" value="<?php echo $fp_value; ?>">
        </div>  
      
    <?php
        if (!empty($successmsg))
        {
            echo "
            <div class='alert alert-warning alert-dismissible fade show' role='alert'>
                <strong> $errormsg</strong>
                <button type= 'button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'> </button>
            </div>
            ";
        }
    ?>
        <div>
            <button type="submit" class="btn btn-primary"> Submit </button>
        </div>  

        <div>
            <a class="btn btn-outline-primary" href="/LOC/first.php" role="button"> Cancel </button>
        </div>  
    </form>
    
</main>
</body>
</html>

Have tried this version of code,

if(isset($_POST['edit']))
{   
    $id = $_POST['id'];
    
    $name=$_POST['name'];
    $matric_id=$_POST['matric_id'];
    
    // checking empty fields
    if(empty($name) || empty($matric_id)) {          
        if(empty($name)) {
            echo "<font color='red'>Name field is empty.</font><br/>";
        }
                
        if(empty($matric_id)) {
            echo "<font color='red'>Email field is empty.</font><br/>";
        }       
    } else {    
        //updating the table
        $result = mysqli_query($mysqli, "UPDATE info SET name='$name',matric_id='$matric_id' WHERE id=$id");
        
        //redirectig to the display page
        header("Location: first.php");
    }
}
?>
<?php
//getting id from url
$id = $_GET['id'];

//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM info WHERE id=$id");

while($res = mysqli_fetch_array($result))
{
    $name = $res['name'];
    $email = $matric_id['matric_id'];
}
?>

Google maps Geocoding API error [Unhandled promise rejection: TypeError: undefined is not an object (evaluating ‘data.results[0].geometry’)]

I am facing an error regarding Geocoding API.

I am trying to get the coordinates when the user presses this button

<TouchableOpacity
            style={tw`flex-row items-center p-5`}
            onPress={() => {
              dispatch(
                setDestination({
                  geometry: {
                    location: { lat: 3.0023237, lng: 101.7059165 },
                  },
                  description,
                }),
              );
            }}
          >

Here is the full code of Map.js:

import { StyleSheet, Text, View } from 'react-native';
import React, { useEffect, useRef, useState } from 'react';
import MapView, { Marker } from 'react-native-maps';
import tw from 'twrnc';
import { useDispatch, useSelector } from 'react-redux';
import {
  selectDestination,
  selectOrigin,
  setDestination,
  setTravelTimeInformation,
  setMarker,
} from '../slices/navSlice';
import MapViewDirections from 'react-native-maps-directions';
import { GOOGLE_MAPS_APIKEY } from '@env';



const Map = () => {
  const origin = useSelector(selectOrigin);
  const destination = useSelector(selectDestination);
  const mapRef = useRef(null);
  const dispatch = useDispatch();

  useEffect(() => {
    if (!origin || !destination) return;
    mapRef.current.fitToSuppliedMarkers(['origin', 'destination'], {
      edgePadding: { top: 50, right: 50, bottom: 50, left: 50 },
    });
  }, [origin, destination]);

  useEffect(() => {
    if (!origin || !destination) return;

    const getTravelTime = async () => {
      fetch(
        `https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${destination.description}&origins=${origin.description}&units=imperial&key=${GOOGLE_MAPS_APIKEY}`,
      )
        .then((res) => res.json())
        .then((data) => {
          dispatch(setTravelTimeInformation(data.rows[0].elements[0]));
        });
    };
    getTravelTime();
  }, [origin, destination, GOOGLE_MAPS_APIKEY]);

  useEffect(() => {
    if (!origin || !destination) return;

    const getCoordinates = async () => {
      fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${destination.description}&key=${GOOGLE_MAPS_APIKEY}`,
      )
        .then((res) => res.json())
        .then((data) => {
          dispatch(setDestination(data.results[0].geometry.location));
        });
    };
    getCoordinates();
  }, [destination, GOOGLE_MAPS_APIKEY]);

  return (
    <MapView
      ref={mapRef}
      showsUserLocation
      style={tw`flex-1`}
      mapType="mutedStandard"
      initialRegion={{
        latitude: origin.location.lat,
        longitude: origin.location.lng,
        latitudeDelta: 0.005,
        longitudeDelta: 0.005,
      }}
    >
      {origin && destination && (
        <MapViewDirections
          origin={origin.description}
          destination={destination.description}
          apikey={GOOGLE_MAPS_APIKEY}
          strokeWidth={3}
          strokeColor="blue"
        />
      )}
      {origin?.location && (
        <Marker
          pinColor={'green'}
          coordinate={{
            latitude: origin.location.lat,
            longitude: origin.location.lng,
          }}
          title="Origin"
          description={origin.description}
          identifier="origin"
        />
      )}

      {destination?.location && (
        <Marker
          coordinate={{
            latitude: destination.location.lat,
            longitude: destination.location.lng,
          }}
          title="Destination"
          description={destination.description}
          identifier="destination"
        />
      )}
    </MapView>
  );
};

export default Map;

The exact part that causes the error is this:

   useEffect(() => {
    if (!origin || !destination) return;

const getCoordinates = async () => {
  fetch(
    `https://maps.googleapis.com/maps/api/geocode/json?address=${destination.description}&key=${GOOGLE_MAPS_APIKEY}`,
  )
    .then((res) => res.json())
    .then((data) => {
      dispatch(setDestination(data.results[0].geometry.location));
    });
};


  getCoordinates();
  }, [destination, GOOGLE_MAPS_APIKEY]);

it comes from this:

 .then((data) => {
      dispatch(setDestination(data.results[0].geometry.location));
    });

The error:

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'data.results[0].geometry')]
at node_modulespromisesetimmediatecore.js:null in tryCallOne
at node_modulespromisesetimmediatecore.js:null in setImmediate$argument_0
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:null in _allocateCallback$argument_0
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:null in _callTimer
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:null in _callReactNativeMicrotasksPass
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:null in callReactNativeMicrotasks
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:null in __callReactNativeMicrotasks
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:null in __guard$argument_0
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:null in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:null in flushedQueue

the reducer js file:
NavSlice.js

import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  origin: null,
  destination: null,
  travelTimeInformation: null,
  marker: {},
};

export const navSlice = createSlice({
  name: 'nav',
  initialState,
  reducers: {
    setOrigin: (state, action) => {
      state.origin = action.payload;
    },
    setDestination: (state, action) => {
      state.destination = action.payload;
    },
    setTravelTimeInformation: (state, action) => {
      state.travelTimeInformation = action.payload;
    },
  },
});

export const { setOrigin, setDestination, setTravelTimeInformation } = navSlice.actions;


export const selectOrigin = (state) => state.nav.origin;
export const selectDestination = (state) => state.nav.destination;
export const selectTravelTimeInformation = (state) => state.nav.travelTimeInformation;
export default navSlice.reducer;

store.js

import { configureStore } from '@reduxjs/toolkit';
import navReducer from './slices/navSlice.js';

export const store = configureStore({
  reducer: {
    nav: navReducer,
  },
});

I am not very sure on why this is not working, any ideas? This should work similarly to when you set the destination to your favorite location. Like Uber.

Navigate with page reload using react router

My application uses a Laravel backend and a React frontend. Ordinarily, I would use e.preventDefault() so that there are no page reloads. The issue I am having is that if I login or logout without a page refresh, it causes a CSRF mismatch on future requests. So I’m okay with the page refresh. However, when I remove e.preventDefault(), the form data becomes appended to the URL. The best solution I have been able to come up with is this:

  let csrfToken = document.head.querySelector('meta[name="csrf-token"]').content;

  const navigate = useNavigate()

  const handleLogin = async (e) => {
    e.preventDefault()
      axios.post('login', {email, password}, {
        'X-CSRF-TOKEN': csrfToken
      })
      .then(() => {
        setLoginStatus(true)
        navigate('/')
        window.location.reload();
      })
  }

This essentially works, but I don’t like it. What happens is that the view is updated with the Component at ‘/,’ and then the page refreshes. It just looks weird. All I want is for the Component at ‘/’ to be rendered upon the form’s submission with a page reload. Keeping in mind my problem with removing e.preventDefault(), where the form data gets added to the URL.

Not working UseState when page refreshing

In my application, I am trying to load array details according to the id that the user selected. But the application works when I only click the id 1 of the main array. When the page is loading, I have set a default value for useState (id) for the second array. And I use a Chip component to show the value responsible for each id of the second array. When I click a chip component I set id of that particular object using useState. I found that when the page is refreshing the id value is not properly set even though I have defined a default value. Please help me to solve this. This is my code.

const GradingList = ({DATA, defaultId, manufactureNumber}) => {
  const [isModalShow, setModalShow] = React.useState(false);
  const [id, setId] = React.useState(DATA[0].id);
  const [details, setdetails] = React.useState([]);
  const [selectIndex, setSelectIndex] = React.useState(0);
  const [gradesList, setGradesList] = React.useState(grades);
  const [selectedGrade, setSelectGrade] = React.useState(null);
  const [weight, setWeight] = React.useState(0);

  const commonInfoUpdateRef = React.useRef(null);
  const customActionSheetRef = React.useRef(null);

  React.useEffect(() => {
    dropDown();
  });

  const dropDown = () => {
    if (isModalShow) {
      commonInfoUpdateRef.current.show();
    } else {
      commonInfoUpdateRef.current.hide();
    }
  };

 

  const onPressChip = list => {
    const arr = list.filter(ele => {
      return ele.id === id;
    });

    const dhool = DATA.filter(ele => {
      return (
        ele.manufactureName === manufactureNumber.manufactureName
      );
    });

    const found = dhool.find(obj => {
      return obj.id === id;
    });

    //console.log(,'55555555555555555555')
    let sum = arr.reduce(function (prev, current) {
      return prev + +current.weight;
    }, 0);

    const restWeight = found.weight - sum;

    return (
      <View>
        <View style={{flexDirection: 'row-reverse', marginTop: 2}}>
          <Button
            disabled={false}
            icon={'plus'}
            mode="contained"
            onPress={() => {
              setModalShow(true);
              setGradeError(true);
              setWeightError(true);
            }}
            color={'#0AB155'}
            style={{left: 0, marginTop: 5}}>
            {'Add Grade'}
          </Button>
        </View>
        <View style={{marginLeft: '20%', marginTop: 20}}>
          {found && cardTextRow('Total Weight (KG)', String(found.weight))}
          {cardTextRow('Rest Weight (KG)', String(restWeight))}
        </View>
        <View>
          {arr?.map((item, index) => {
            return (
              <Card style={{marginTop: 10}}>
                <Card.Content>
                  <View>{cardItems(item)}</View>
                  <View style={{flexDirection: 'row-reverse', marginTop: 2}}>
                    <Button
                      disabled={false}
                      icon={'circle-edit-outline'}
                      mode="contained"
                      onPress={() => {
                        setModalShow(true),
                          setEditGrade(true),
                          setSelectedCardIndex(index);
                        const obj = Object.assign({}, item);
                        setSelectedItem(obj);
                        setGrade(obj ? obj.name : '');
                        setWeight(obj ? obj.weight : '');
                        setWeightError(false);
                        setGradeError(false);
                      }}
                      color={'#0aa6b1'}
                      style={{left: 0, marginTop: 5}}>
                      {'Edit'}
                    </Button>
                  </View>
                </Card.Content>
              </Card>
            );
          })}
        </View>
      </View>
    );
  };


  return (
    <SafeAreaView style={styles.container}>
      <View style={{height: 40, flexDirection: 'row', alignSelf: 'auto'}}>
        {DATA?.map((item, index) => {
          const selected = index === selectIndex;
          return (
            <View>
              <Chip
                onPress={() => {
                  setSelectIndex(index);
                  setId(item.id);
                }}
                style={{
                  marginHorizontal: 5,
                  backgroundColor: selected ? '#0AB155' : '#d4d6d4',
                  borderColor: '#9fa19f',
                }}
                selectedColor={selected ? '#fff' : '#000'}
                selected={selected}>
                {item.name}
              </Chip>
            </View>
          );
        })}
      </View>
      <View>{onClickAddButton()}</View>
      <View>{onPressChip(details)}</View>
    </SafeAreaView>
  );
};

export default GradingList;

Facing problem in opening files in syncfusion File Manager

Greetings!

currently I’m working on syncfusion file manager and facing a problem, I’m unable to open a pdf , docx, text , xlxs and any kind of files on right click open options,

Can you please guide me in this.

I am following documentation but I am unable to get guidance through it, I want to open pdf , docx, text , xlxs and any kind of files on right click open option

“Cannot GET /” for PUT request handler [closed]

I tried the same code as it was posted on a page to get make a put request in a simplest form but get a Cannot GET / not even a Cannot PUT / error

var express = require('express');
var app = express();
var PORT = 3000;

  
app.put('/', function (req, res) {
  res.send('PUT request to homepage')
})

  
app.listen(PORT, function(err){
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
}); 

How to optimize memory usage in javascript code

I’m extremely new to javascript and html, and I’ve been trying to make an animated game for a few months now. Everything was going smoothly until a few days ago the frame rate suddenly dropped. I went through a few stackoverflow questions and I got to the conclusion that it was because my code was really messy and I had to optimize it. Since I’m really new, I don’t understand how I would exactly do that.

Here is my index.js:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');

//adjust canvas width/height to take full screen
canvas.width= 1680;
canvas.height= 945;

//img function to easily import images
function img(file){
    const image = new Image();
    image.src = 'sprites/' +file;
    return image;
}

//declaring images
  const platformImg = img('platform.png');
  const bg1 = img('bg1.png');
  const bg2 = img('bg2.png');
  const bg3 = img('bg3.png');
  const bg4 = img('bg4.png');
  const bg5 = img('bg5.png');
  const idle_right = img('idle_right.png');
  const run_right = img('run_right.png');
  const idle_left = img('idle_left.png');
  const run_left = img('run_left.png');
  const platform_bottom = img('platform_bottom.png');
  const platform_sblock = img('platform_sblock.png');
  const platform_upperleft = img('platform_upperleft.png');
  const platform_upperright = img('platform_upperright.png');
  const platform_zblock = img('platform_zblock.png');

//Declaring variables
const gravity = 0.5; //Global Gravity
var firstSplash = 1;
var lastSplash = 210;
var splash = new Image;
var timer = setInterval( function(){
  if (firstSplash>lastSplash){
    clearInterval( timer );
  }else{
    splash.src = "./sprites/Splash/splash("+( firstSplash++ )+").jpg";
  }
}, 1000/30 ); //Draw at 30 frames per second



class Player {
  constructor(){ // Player Position/Width/Height
    this.position = {
      x: 100,
      y: 667
    }
    this.velocity = {  // Player Gravity
      x: 0,
      y: 0
    }

    this.width = 104;
    this.height = 128;
    this.image = idle_right;
    this.frames = 0;
    this.sprites = {
      idle: {
        right: idle_right,
        left: idle_left,
        cropWidth: 208,
        cropHeight: 256,
        frameLimit: 36
      },
      run: {
        right: run_right,
        left: run_left,
        cropWidth: 208,
        cropHeight: 272,
        frameLimit: 48
      }
    }
    this.currentSprite = this.sprites.idle.right;
    this.currentCropWidth = 208;
    this.currentCropHeight = 256;
    this.currentFrameLimit = 36;
  }

  // Make Player Visible
  draw(){
    ctx.drawImage(
      this.currentSprite,
      this.currentCropWidth * this.frames,
      0,
      this.currentCropWidth,
      this.currentCropHeight, 
      this.position.x, 
      this.position.y, 
      this.width, 
      this.height)
  }

  update(){ 
    this.frames++;
    if (this.frames>=this.currentFrameLimit) this.frames = 0;
    this.draw();
    this.position.x += this.velocity.x;
    this.position.y += this.velocity.y;
    
    
    // Gravity to Player
    if (this.position.y + this.height +  this.velocity.y <= canvas.height)
      this.velocity.y += gravity;
  }
}

class Platform {
  constructor({x, y, image}) {
    this.position = {
      x,
      y
    }

    this.width = 600
    this.height = 180
    this.image = image
  }

  draw() {
    ctx.drawImage(this.image, this.position.x, this.position.y)
  }
}

class Decoration {
  constructor({x, y, image}) {
    this.position = {
      x,
      y
    }

    this.width = 16800
    this.height = 945
    this.image = image
  }

  draw() {
    ctx.drawImage(this.image, this.position.x, this.position.y)
  }
}

//Declaring variables
let player = new Player();
let platforms = [new Platform({
  x: -1,
  y: 800,
  image: platformImg
}),
  new Platform({
    x: 600 -1,
    y: 800,
    image: platformImg
  })]
let decorations = [
  new Decoration({
    x:0,
    y:0,
    image: bg1
  }),
  bg2Deco = new Decoration({
    x:0,
    y:0,
    image: bg2
  }),
  bg3Deco = new Decoration({
    x:0,
    y:0,
    image: bg3
  }),
  bg4Deco = new Decoration({
    x:0,
    y:0,
    image: bg4
  }),
  bg5Deco = new Decoration({
    x:0,
    y:0,
    image: bg5
  })
]
const keys = {
  right:{
    pressed: false
  },
  left:{
    pressed: false
  }
}

let scrollOffset = 0;

//Levels
let level = 1
let levels = {
  1: {
    init: () => {
      player = new Player();
      platforms = [new Platform({
        x: -1,
        y: 800,
        image: platformImg
      }),
      new Platform({
        x: 600 -1,
        y: 800,
        image: platformImg
      })]
      decorations = [
        new Decoration({
          x:0,
          y:0,
          image: bg1
        }),
        bg2Deco = new Decoration({
          x:0,
          y:0,
          image: bg2
        }),
        bg3Deco = new Decoration({
          x:0,
          y:0,
          image: bg3
        }),
        bg4Deco = new Decoration({
          x:0,
          y:0,
          image: bg4
        }),
        bg5Deco = new Decoration({
          x:0,
          y:0,
          image: bg5
        })
      ]
      scrollOffset = 0;
    }
  }
}


function drawSplash(){
  splash.onload = function(){
    ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
    ctx.drawImage(splash, 0, 0, ctx.canvas.width, ctx.canvas.height);
  };
}


function gameStart(){
    ctx.fillStyle = 'black'
    ctx.fillRect(0,0,canvas.width, canvas.height)
    document.getElementById("btnStart").remove();
    player.draw();
    animate();
}


function animate(){ // Animate
  requestAnimationFrame(animate);
  ctx.fillStyle = 'white';
  ctx.fillRect(0,0,canvas.width, canvas.height)
 
  decorations.forEach(Decoration =>{
    Decoration.draw();
  });

  platforms.forEach(platform =>{
    platform.draw();
  });

  player.update();

  // Hold left/right for moving player
  if (keys.right.pressed && player.position.x < 400){
    player.velocity.x = 5
  } else if ((keys.left.pressed && player.position.x > 100) || (keys.left.pressed && scrollOffset === 0 && player.position.x > 0)) {
    player.velocity.x = -5
  } else {
    player.velocity.x = 0
  
    if (keys.right.pressed){
      scrollOffset += 5;
      platforms.forEach(platform =>{
        platform.position.x -=5 
      });
      bg2Deco.position.x -= 3;
      bg3Deco.position.x -= 4;
      bg4Deco.position.x -= 5;
      bg5Deco.position.x -= 6;
    } else if (keys.left.pressed && scrollOffset > 0){
      scrollOffset -= 5;
      platforms.forEach(platform =>{
        platform.position.x +=5 
      });
      bg2Deco.position.x += 3;
      bg3Deco.position.x += 4;
      bg4Deco.position.x += 5;
      bg5Deco.position.x += 6;
    }
  }

  // Platform detection for player
  platforms.forEach(platform =>{
    if (player.position.y + player.height <= platform.position.y && player.position.y + player.height + player.velocity.y >= platform.position.y && player.position.x + player.width >= platform.position.x && player.position.x <= platform.position.x + platform.width) {
      player.velocity.y = 0;
    }
  });

//win condition
  if(scrollOffset > 5000){
    console.log("you win");
  }

//lose condition
  if (player.position.y > canvas.width){
    levels[level].init();
  };
}

document.body.addEventListener('keydown', keyDown);
document.body.addEventListener('keyup', keyUp);

function keyDown(event){
    if(event.code == "ArrowUp"){
        if(event.repeat){return}
        else player.velocity.y -= 10;
    }

    if(event.code == "ArrowLeft"){
      keys.left.pressed = true;
      player.currentSprite = player.sprites.run.left;
      player.currentCropWidth = player.sprites.run.cropWidth;
      player.currentCropHeight = player.sprites.run.cropHeight;
      player.currentFrameLimit = player.sprites.run.frameLimit;
    }

    if(event.code == "ArrowRight"){
      keys.right.pressed = true;
      player.currentSprite = player.sprites.run.right;
      player.currentCropWidth = player.sprites.run.cropWidth;
      player.currentCropHeight = player.sprites.run.cropHeight;
      player.currentFrameLimit = player.sprites.run.frameLimit;
    }
}

function keyUp(event){
  if(event.code == "ArrowUp"){
      player.velocity.y -= 5;
  }

  if(event.code == "ArrowLeft"){
    keys.left.pressed = false;
    player.currentSprite = player.sprites.idle.left;
    player.currentCropWidth = player.sprites.idle.cropWidth;
    player.currentCropHeight = player.sprites.idle.cropHeight;
    player.currentFrameLimit = player.sprites.idle.frameLimit;
  }

  if(event.code == "ArrowRight"){
    keys.right.pressed = false;
    player.currentSprite = player.sprites.idle.right;
    player.currentCropWidth = player.sprites.idle.cropWidth;
    player.currentCropHeight = player.sprites.idle.cropHeight;
    player.currentFrameLimit = player.sprites.idle.frameLimit;
  }
}
drawSplash();

Any help would be appreciated, thank you!

Edge-Js Breaking on Node 18.13 Upgrade

I have a nodejs project that uses edge-js to read a dll file. Everything works fine on node version 16.17.0 but on upgrading to node 18.13.0 I get the error “edge is not precompiled for Node version 18.13”. The version of edge-js is 16.6.0. If I update edge-js to 19.3.0 it can’t read the dll – “could not load file or assembly”

What could be going on?

This is the code snippet that calls edge

var edge = require('edge-js');
var path = require('path');
var authenticate = edge.func({
        source: path.join(__dirname, 'checkpass.csx'),
        references: [path.join(__dirname, '../../api/ASInterface.dll'),
            path.join(__dirname, '../../api/ASUtilities.dll') ]
        });

This is the package.json

{
  "name": "node",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./www"
  },
  "dependencies": {
    "async": "^2.6.4",
    "bcrypt": "^5.0.1",
    "body-parser": "^1.18.3",
    "child_process": "^1.0.2",
    "cookie-parser": "^1.4.5",
    "dateformat": "^3.0.3",
    "deasync": "^0.1.24",
    "edge-js": "^16.6.0",
    "ejs": "^3.1.7",
    "express": "^4.16.4",
    "fast-xml-parser": "^3.17.4",
    "follow-redirects": "^1.14.7",
    "fs-extra": "^7.0.1",
    "fstream": "^1.0.12",
    "gettext-parser": "^3.1.1",
    "glob": "^7.2.3",
    "graceful-fs": "^4.2.4",
    "gridstack": "^1.1.2",
    "hash-files": "^1.1.1",
    "he": "^1.2.0",
    "jsonata": "^1.8.3",
    "jsonfile": "^5.0.0",
    "kapsule": "^1.13.3",
    "line-reader": "^0.4.0",
    "lodash": "^4.17.21",
    "mime-types": "^2.1.27",
    "minimatch": "^5.1.0",
    "mkdirp": "^0.5.4",
    "moment": "^2.29.4",
    "moment-range": "^4.0.2",
    "moment-timezone": "^0.5.31",
    "morgan": "^1.10.0",
    "morgan-json": "^1.1.0",
    "msnodesqlv8": "^2.4.8",
    "mssql": "^5.1.2",
    "multer": "^1.4.1",
    "node-esapi": "^0.0.1",
    "node-fqdn": "^1.1.1",
    "node-gettext": "^2.0.0",
    "node-windows": "^1.0.0-beta.5",
    "pettan": "^1.1.0",
    "randomstring": "^1.1.5",
    "rimraf": "^3.0.2",
    "rotating-file-stream": "^1.4.0",
    "serve-favicon": "^2.5.0",
    "sql-formatter": "^2.3.3",
    "tedious": "14.1.0",
    "underscore": "^1.13.1",
    "unzipper": "^0.10.11",
    "winreg": "^1.2.4",
    "winston": "^3.7.2",
    "winston-daily-rotate-file": "^4.5.0",
    "xml2js": "^0.4.23"
  }
}

React app server not running on 127.0.0.1

I’ve recently built a project using create-react-app. Everything is fine until today.

I run npm start as usual and try to visit http://localhost:3000. But I got LOCALHOST REFUSED CONNECTION error. And I got this on terminal’s output in vscode.

Local:            http://localhost:3000
On Your Network:  http://172.24.194.157:3000

I made a small test: using vite to create a react app and npm run dev. And it’s just fine to visit http://localhost:5173.

At first I thought it might be a problem with port. But turns out not. Because http://172.24.194.157:3000 is ok to develop my react-app.

So I guess, my browser resolute localhost to 127.0.0.1, and 127.0.0.1:3000 is not available due to react-scripts start serve the app on 172.24.194.157:300.

But WHY is that happen? I made no changes to any config.(though I didn’t open this project for about 2 weeks). It would be a great help if anyone can answer this. Thanks!

ENV INFO:

wsl1 in windows 11 (Ubuntu 20.04)
node: v16.9.0
npm: 8.19.3

debugger in JS of HTML File

https://github.com/davidflanagan/jstdg7/blob/master/ch15/guessinggame.html
In the sourcecode above, I added debugger in line 158 like below:
let gamestate = GameState.fromURL(window.location) || GameState.newGame();debugger;

Also added debugger in line 55 like below:
let url = new URL(window.location);debugger;

But when open the file(using Chome), typed guess number, then press enter. Either way, it does NOT trigger the bugger I set.

Have I missed anything? Thanks a lot.

I expect the my actions(load the html and submit my guess numbers) will trigger the dubugger I set.

Geocode runs with Google MAP API

I try to code Google MAP API by trying its documentation, i don’t why it doesn’t work. I try to get location address with using longitide and latitude.

Error Geocode Image

if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function(position) {
                        console.log(position);
                        $('#latitude').html(position.coords.latitude);
                        $('#longitude').html(position.coords.longitude);
                        map = new google.maps.Map(document.getElementById("location"), {
                            center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                            zoom: 21,
                            mapId: "c6b860682cMAP_Id",
                            mapTypeId: google.maps.MapTypeId.ROADMAP
                        });
                        $("#location").height(360); 
                        $("location").width(700); 

                        marker = new google.maps.Marker({
                            position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                            map,
                            title: "Here is Nigel"
                        });
                        var geoCoder = new google.maps.Geocoder();
                        var latitude = marker.getPosition().lat();
                        var longitude = marker.getPosition().lng();
                        // Alamat Start
                        var address = geoCoder.geocode({ latLng: new google.maps.LatLng(position.coords.latitude, position.coords.longitude) }).then((result) => {
                            const { results } = result;
                            map.setCenter(results[0].geometry.location);
                            marker.setPosition(results[0].geometry.location);
                            marker.setMap(map);
                            responseDiv.style.display = "block";
                            response.innerText = JSON.stringify(result, null, 2);
                            return results[0].formatted_address;
                        }).catch((e) => {
                            alert("Geocode was not successful for the following reason: " + e);
                        });
                        $('#alamat').html(address);
                        // Alamat End
                    });
                }

I can get address from geocode code which runs with Google Map API