User is instantly logged out when logging in using firebase as authenticator on react

I’m new to react/firebase and I’ve recently been working on a project that involves a user signing into the website in order to access different aspects of a navigation bar, however for some reason, everytime a user logs in, they are briefly shown the correct navigation bar as well as are logged in, but shortly thereafter, they are logged out and sent back to the login page. Debugging the code, I found that for some reason, once a user clicks on the sign in button, the handleSignout function is ran along with the handleform submission function.

Attached is my Navbar along with the signout function because of the Sign out button in it. When I remove the onClick = {handleSignout()} from the sign out button, the user is not instantly signed out, but it defeats the purpose of having the button.

import {
  Nav,
  NavLink,
  Bars,
  NavMenu,
  NavBtnLink,
} from './Navbar';
import { auth, fdb } from '../../firebase';
import { signOut } from 'firebase/auth';
import { updateDoc, doc } from 'firebase/firestore';
import { useContext } from 'react';
import { AuthContext } from '../../context/auth';
import { useNavigate } from 'react-router-dom';

const Navbar = () => { 
  const Navigate = useNavigate();
  const {user} = useContext(AuthContext);
  
  const handleSignout = async() => {
    await updateDoc(doc(fdb,'users', auth.currentUser.uid), {
      isOnline: false,
    });
    await signOut(auth);
    Navigate('/Login')
  };
  return(

    <Nav>
      <NavLink to='/'>
        <h1>logo</h1>
      </NavLink>
          {user ? (
            <>
          
          <Bars />
          <NavMenu>
            <NavLink to= '/Listings'>
                Listings
            </NavLink>
            <NavLink to= '/Post'>
                Post
            </NavLink>
            <NavLink to= '/contact'>
                Contact
            </NavLink>
            <NavLink to= '/profile'>
                Profile
            </NavLink>
            <NavBtnLink to='/' onClick={handleSignout()}>
                Log Out
            </NavBtnLink>
          </NavMenu>
          </>
          ) : (
          <>  
              <NavMenu>
              <NavBtnLink to='/Login'>
                  Log In / Register
              </NavBtnLink>
          </NavMenu>

          </>
          )}
          
        </Nav>
  )
};


export default Navbar;

Here is my login.js

import React from 'react'
import { useRef, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { auth, fdb } from '../firebase'
import { signInWithEmailAndPassword } from 'firebase/auth'
import { updateDoc, doc } from 'firebase/firestore'

const Login = () => {
  const emailRef = useRef();
  const errRef = useRef();

  const [email, setEmail] = useState('');
  const [pwd, setPwd] = useState('');
  const [errMsg, setErrMsg] = useState('');
  const Navigate = useNavigate();

  
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const userinfo = await signInWithEmailAndPassword(auth,email,pwd);
      await updateDoc(doc(fdb, 'users', userinfo.user.uid),{
        isOnline: true,
      })
      Navigate('/')
    } catch (e) {
      alert(e)
    }

    
  }

  return (
    <div> 
      <div className="loginBody">
        <p ref = {errRef} className= {errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
        <h1 className='loginHeader'>Login</h1>
        <form onSubmit={handleSubmit}>
          <div className="email">
            <label htmlFor="email" id='userLabel'>Email</label>
            <br/>
            <input 
              type="text" 
              id="email" 
              ref = {emailRef} 
              autoComplete = "off" 
              onChange = {((e)=> setEmail(e.target.value))} 
              value={email}
              required
              />
          </div>
          <div className="pwd">
            <label htmlFor="password">Password</label>
            <br/>
            <input 
              type="password" 
              id="password" 
              autoComplete = "off" 
              onChange = {((e)=> setPwd(e.target.value))} 
              value={pwd}
              required
              />
         </div>
         <button id='signIn'>Sign In</button>
        </form>
        <p className='needAcc'>
          Need an Account? <br/>
          <span className="line">
            <Link to="/Register" id='signUpLink'>Sign Up</Link>
          </span>
        </p>
      </div>
    </div>
  )
}

export default Login

I need help passing the parameters of onclick to a function in Javascript

This is for a school project, I’m still super new to JS. I’m trying to create a slideshow that replaces the main image and loops through different 5 image arrays depending on what button you click. The arrays are supposed to be passed to the one function displayPics. I am also very confused about how to group all the arrays to run the count through…
It is a total mess but I know it is failing at passing the parameter.
My HTML and Javascript:

  <img
    id="mainImg"
    style=" "
    src="barn.jpeg"
    alt="barn" >

<button onclick="displayPics('Goats');" >Goats</button>
<button onclick="displayPics('Cows');" >Cows</button>
<button oneclick="displayPics('Donkeys');">Donkey</button>

    <script >
var mainImg = document.getElementById('mainImg');
var imageIndex = 0;

function displayPics(x){
    var pictures = ['goats1.jpeg','goats2.jpeg','goats3.jpeg','goats4.jpeg','goats5.jpeg'];
    var pictures2 = ['cows1.jpeg','cows2.jpeg','cows3.jpeg','cows4.jpeg','cows5.jpeg'];
    
  for (var count = 0; count < pictures.length; count++) {
    task(count);
    
function task(count){
      setTimeout(function(){
        if ("displayPics()" == "displayPics('Goats')"){
            pictures = pictures[0];}
          }
      
          else if ("displayPics()" == "displayPics('Cows')"){
  pictures = pictures2[0]; }
    }
    }
    }
    </script>

Problems locating ‘rows’ within JavaScript arrays

I am finding JS arrays to be maddening, I am attempting to locate the ‘row’ of a passed item in a (JS) 2D array. I would not be having these issues in other languages. I have attempted two completely different approaches, neither of which is providing a proper result. This is how I am creating the 2D array, and it seems to be functional:

var _rooms = [];

var _User = function(roomNo, name) {
  this.roomNumber = roomNo;
  this.LeaderName = name;
};

_rooms.push( new _User(1, "katy") );
_rooms.push( new _User(23, "Sara") );

Here is the first attempt to locate a row # of a passed ‘name’:

function findPosition(str) {
var _locater, _sought, _seeks;  
  
 for (_locater = 0; _locater < _rooms.length; _locater++) {
 _seeks = _rooms[_locater];
 _sought = _seeks.indexOf(str);     
   if (_sought >= 0) {
     return "row: " + _locater + ", col: " + _sought;
   }
 }
}

console.log(findPosition('Sara'));
//SOURCE:  "https://stackoverflow.com/questions/46540878/finding-row-and-column-of-a-multidimensional-array-in-javascript"

This throws a typeError, something like “_seeks.indexOf(str) is not a function”. Here is another attempt:

function indexOf2dArray(itemtofind) {
var _sought
  
_sought = [].concat.apply([], ([].concat.apply([], _rooms))).indexOf(itemtofind);
            
// return "false" if the item is not found
if (_sought === -1) { return false; }

// Use any row to get the rows' array length
// Note, this assumes the rows are arrays of the same length
numColumns = _rooms[0].length;

// row = the index in the 1d array divided by the row length (number of columns)
row = parseInt(_sought / numColumns);

// col = index modulus the number of columns
col = _sought % numColumns;

return [row, col]; 
}

console.log("Sara is located: " + indexOf2dArray("Sara"))  
console.log("katy is located: " + indexOf2dArray("katy")) 
//SOURCE:  https://lage.us/Javascript-Item-in-2d-Array-Using-indexOf.html

The result of this approach is “false” for each of the console.log statements. Can anybody suggest a reliable method to locate the ‘row’ a searched item appears in a JavaScript 2D array…? Any suggestions much appreciated.

Asp.Net SignalR sometimes not connected and doesn’t show any error codes

I have a project that uses SignalR to make three web pages communicate with each other.
Open with chrome browser on different computers, only one of them can work normally.
After further inspection, on a computer with a working chrome browser, an exception will also occur when the Edge browser is opened.

Further explanation, I have three webpages A, B and C, and I have joined the same group. Under normal circumstances, if any webpage triggers the function, the other two will receive the message.
Webpage B does not receive any messages at all, and there is no error message about abnormal connection. However, the function can still be triggered normally on page B, and pages A and C receive messages normally.

I use the following code to confirm that SignalR is working

    public override Task OnConnected()
{
    return base.OnConnected();
}


public override Task OnDisconnected()
{
    return base.OnDisconnected();
}

When my SignalR is connected normally, OnConnected() is triggered, and when the webpage is closed, OnDisconnected() is triggered.

Use Debug in any browser on any computer, A and C webpages are triggered normally.

The B page is almost never triggered in the chrome browser of some computers, or the Edge browser of any computer (there is a small chance that it will trigger and work normally).

In the state where OnConnected() is not triggered, the B webpage can still send the SignalR function, but cannot receive messages.

Code changed from Group to All

Clients.Group(group_name).startPartIdSend(part_code);
↓
Clients.All.startPartIdSend(part_code);

Still can’t receive messages, so I think it’s not the reason for the group.
I really don’t have any idea, can someone help me?

The code for using SignalR on page B is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Human_anatomy.aspx.cs" Inherits="ThreeDirectionImages_Human_anatomy" %>

<!DOCTYPE HTML>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>Human_anatomy_Display</title>
    <script src="../Scripts/jquery-3.4.1.min.js"></script>   
    <script src="../Scripts/jquery.signalR-2.4.1.min.js"></script>
    <script src="../signalr/hubs"></script>

    <script>

    $(document).ready(function () {

      var chat = $.connection.chatHub;

      $.connection.hub.start().done(function () {

          var userID = window.opener.document.getElementById("roomName").value;//Get UserID
          console.log("userID" + ":" + userID)
          chat.server.updateWeb("ThreeDirectionImages", userID);//join group

      });

    });

    </script>

Startup.cs:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(IPCTest.Startup))]
namespace IPCTest
{
    public partial class Startup {
        public void Configuration(IAppBuilder app) {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}

ChatHub.cs usage example:

    public void CoordinateTransferServerSendToClient(float x, float y, int z, int part_code, int user_id)
{
    Connector source = connectionlist.Find(a => a.connectionId.Contains(Context.ConnectionId));
    string group_name = source.groupName;
    Clients.Group(group_name).serverSendToClient(x, y, z, part_code, user_id);
    //Clients.All.serverSendToClient(x, y, z, part_code, user_id);
}

browser version

Implementing flood fill BFS

I’m trying to find if a certain area is reachable within a set of moves using a flood fill breadth first search algorithm, but I’m having trouble implementing the algorithm.
I have a grid here

        let map = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, -1, 0, 0],
            [0, 0, -1, 1, -1, 0, 0],
            [0, 0, -1, 0, 0, 0, 0],
            [0, 0, -1, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
        ]

Where 1 is my starting position and -1 represents blocked or inaccessible tiles.

From what I understand of flood fill BFS is your first node is the starting position, in my case it’s where my map is [y,x]==1 and push this into your que. You then iterate through each element of your que. Then find the neighbors for each element, then you check each neighbor if it’s accessible or its visited. And if it’s not visited, you append it to the visited list and lastly append it to your list of reachable tiles.

I’m lost on the algorithm and can’t implement it properly.
Here’s my attempt at the algorithm

<html>

<head>

</head>

<body>
    <canvas id="canvas" width="640" height="480"></canvas>
</body>

<script>
    document.addEventListener("DOMContentLoaded", e => {
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        let mapwidth = 7;
        let mapheight = 7;
        let map = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, -1, 0, 0],
            [0, 0, -1, 1, -1, 0, 0],
            [0, 0, -1, 0, 0, 0, 0],
            [0, 0, -1, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
        ]
        let tw = 25;
        let th = 25;
        function drawgridlines() {
            for (var n = 0; n < mapheight; ++n) {
                for (var m = 0; m < mapwidth; ++m) {
                    ctx.strokeRect(m * th, n * tw, th, tw);
                }
            }
        }
        function fillgrid() {

            for (var n = 0; n < mapheight; ++n) {
                for (var m = 0; m < mapwidth; ++m) {
                    if (map[m][n] == 1) {
                        ctx.fillStyle = "red";
                        ctx.fillRect(m * th, n * tw, th, tw);
                    } else if (map[m][n] == -1) {
                        ctx.fillStyle = "black";
                        ctx.fillRect(m * th, n * tw, th, tw);
                    }
                }
            }
        }
        function filltile(k) {
            let m = k[0];
            let n = k[1];
            ctx.fillRect(m * th, n * tw, th, tw);
        }
        function inbounds(k) {
            let m = k[0];
            let n = k[1];
            return (m >= 0 && m < mapheight && n >= 0 && n < mapwidth);
        }
        function isblocked(k) {
            let m = k[0];
            let n = k[1];
            if (map[m][n] == -1) {
                return true;
            }
            return false;
        }
        function contains(v, k) {
            v.forEach(element => {
                if (element[0] == k[0] && element[1] == k[1]) {
                    return true;
                }
            });
            return false;
        }
        function getneighbors(start) {
            let m = start[0];
            let n = start[1];
            let neighbors = [];
            if (inbounds([m - 1, n])) {
                neighbors.push([m - 1, n]);
            }
            if (inbounds([m, n - 1])) {
                neighbors.push([m, n - 1]);
            }
            if (inbounds([m + 1, n])) {
                neighbors.push([m + 1, n]);
            }
            if (inbounds([m, n + 1])) {
                neighbors.push([m, n + 1]);
            }
            return neighbors;
        }
        function findstart() {
            ctx.fillStyle = "blue";
            for (var m = 0; m < mapheight; ++m) {
                for (var n = 0; n < mapwidth; ++n) {
                    if (map[m][n] == 1) {
                        return [m, n];
                    }
                }
            }
            return undefined;
        }


        ////HELP :(
        function floodfillreachable(start, moves) {
            let que = [];
            let visited = [];
            let flood = [];
            que.unshift(start);
            for (var k = 1; k <= moves; ++k) {
                while (que.length > 0) {
                    let current = que.pop();
                    let n = getneighbors(current);
                    n.forEach(element => {
                        if (!isblocked(element)) {
                            if (!contains(visited, element)) {
                                visited.push(element);
                                flood.push(element);
                            }
                        }
                    });
                }
            }
            return flood;
        }

        function draw(time) {
            ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
            ctx.strokeStyle = "black";
            drawgridlines();
            fillgrid();

            let start = findstart();
            let flood = floodfillreachable(start, 4);
            flood.forEach(element => {
                filltile(element);
            });
            requestAnimationFrame(draw);
        }
        requestAnimationFrame(draw);
    });
</script>

</html>

better-sqlite3 .get() returns undefined

I’m new to bettersql3lite, I tried reading the documentation here:
https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md

and I couldn’t figure out this bug.

I am trying to run a select statement in javascript as follows:

const stmt = db.prepare('select * from table where token = ?').get(token);

where token is an int initialized to be 5000 in this example. db corresponds to the line
const db = require('./database')
Whenever I try running this code and printing out what stmt is, stmt is undefined.

When I try running the same sql query,
select * from table where token = 5000
, in a database browser, I do get a record returned to me as desired. I’m not sure why the above javascript code isn’t working for me, I use it the same way, with strings in place of token, and it behaves as expected (i.e the variable is initialized when there is something in the database that would be returned). I don’t know if strings are the issue, but I’m really confused as to why the above line does not work. Any help is appreciated.

D3.js map visualization v7

Please guys, im trying to understand why this code doesnt work for version 7 of d3.js. Its working for version 4

<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<!-- <script src="https://d3js.org/d3.v4.js"></script> -->
<script src="https://d3js.org/d3.v7.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>

<!-- Create an element where the map will take place -->
<svg id="my_dataviz" width="400" height="300"></svg>

<script>
    // The svg
    var svg = d3.select("svg")
        width = +svg.attr("width"),
        height = +svg.attr("height");
    
    // Map and projection - centraliza em bangkok
    //var projection = d3.geoNaturalEarth1()
    var projection = d3.geoMercator()
        .scale(width / 1.3 / Math.PI)
        .translate([width / 2, height / 2])
        //.center([100, 13])
        //.rotate([0., 0])
        //.parallels([0, 0])
        //.scale(800)
        //.translate([width / 2, height / 2]);

    
    // Load external data and boot
    //d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson", function(data){
    d3.json("world.geojson", function(data){
        // Draw the map
        svg.append("g")
            .selectAll("path")
            .data(data.features)
            .enter().append("path")
                .attr("fill", "#69b3a2")
                .attr("d", d3.geoPath()
                    .projection(projection)
                )
                .style("stroke", "#fff")
    })
</script>

######################################################################################################################################################################################################################################################################################################

Asp/ JavaScript database updates without clicking button ( Ms access 2003-2007)

I’m trying to update the database when the leave button is clicked, however, the function updates even though the button has not been clicked and I am unsure of how to proceed.

 <%<button onclick="dateFunction()"> Leave</button>%> </center>

<% function dateFunction() {
        var d = new Date();
        var conn = new ActiveXObject("ADODB.Connection");
        conn.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source='C:/Users/chenu/Desktop/Q3/leave.mdb'");
        var insert = "UPDATE Appdata SET Leavetime ='" + d + "' WHERE (Firstname = '" + Fname + "' AND Entertime = '" + entrytime + "')";
        conn.Execute(insert);
        conn.Close;
    } %>

javascript to image object so I can get the width, height without displaying, then paint on [duplicate]

I HATE the people that invented javascript so much.

I have an HTML input tag for selecting an image.

I need to get the width height of an image.
I need to create the image object WITHOUT displaying it so I can perform the pixel manipulations BEFORE painting it to the canvas.

FOR THE LOVE OF GOD!!!!

HOW do I create an image object from the input tag and get the width height??????

enter code here 
<input id="my_input" type="file">
<script>
 ; function createimgobj(my_input) {
    let file_dfgh = input.files[0];
    let reader_asdf = new FileReader();
    reader_asdf.readAsDataURL(file_dfgh);
    imageobject=new image(reader_asdf);

    O_width=imageobject.width; alert(O_width) }

    

I am so tired. This opaque language was invented by used car salesmen. It has one job; ruin the internet for everyone. I am being forced to use this language against my will.

Reduce an array of object with same key and concat same property

const res = [
    {
      serviceName: "visa",
      pool: "3g",
      environment: "test-int"
    },
    {
      serviceName: "visa",
      pool: "4g",
      environment: "test-int"
    },
    {
      serviceName: "amex",
      pool: "5g",
      environment: "dev"
    },
    {
      serviceName: "amex",
      pool: "6g",
      environment: "dev"
    }
  ];

Need output in this format:

const output = [
    {
      serviceName: "visa",
      pool: "3g,4g",
      environment: "test-int"
    },
    {
      serviceName: "amex",
      pool: "5g,6g",
      environment: "test-int"
    },
  ]

My code:

const result = res.reduce((acc, ar) => {
      let res = {
        ...acc,
        pool: acc["pool"] + "," + ar.pool
      };
      return res;
    }
  });

Updating 1 table column using ajax in symfony

Ok, so I’ve been really trying to make this work and I keep getting constant obstacles in my way.
I have a star rating system. I want a user to rate someone by selecting the appropriate star.
I’m stuck on returning the value of the rating to the controller and updating a column in my table in the database.
I’m returning this value as JSON, when I do console.log(data) I can clearly see

{
“rating”: 5 }

returned as an object in the console.

Now when I do console.log(url) I get

/editRating/[object HTMLElement]

I can tell that this shouldn’t be what I’m supposed to be getting. Here’s what I’m doing with the controller

/**
     * @Route("/editRating/{id}", name="edit_coach_rating", methods={"PUT"})
     */
    public function editActionRating(?Coach $coach, Request $request):Response
    {
        $data = json_decode($request->getContent());

        if (isset($data->rating) && !empty($data->rating)){
            //data is complete
            $code = 200;

            //verify if the id exists
            if(!$coach){
                $coach = new Coach;

                //change the code
                $code = 201;
            }
            $coach->setRating($data->getRating());

            $em = $this->getDoctrine()->getManager();
            $em->persist($coach);
            $em->flush();

            // Return code
            return new Response('Ok', $code);
        }else{
            // Data is incomplete
            return new Response('Incomplete Data', 404);
        }
    }

The HTTP request is returning

PUT http://127.0.0.1:8000/editRating/[object%20HTMLElement] 404 (Not
Found)

This is what I’m doing with js to deliver the value to the controller

let data = {
    "rating": note}
let url = `/editRating/${coach_id}`
console.log(data)
console.log(url)

let xhr = new XMLHttpRequest

xhr.open("PUT", url)
xhr.send(JSON.stringify(data))

Please you guys I really tried to make this work for several days, I’ve made strides but I really can’t see what else I can do past this point.