why js function works only when I run it with the debugger?

I have a javascript code and in this code I send an axios request to get the user whose password he entered belongs to him.
the problem is:
When I debug the code in the browser debug tool(f12), the code works fine, but if I don’t debug the code, the user login page refreshes again and again and there is no transition to the requested page.
what could be the problem? After all, it seems that the code is correct because when there is debugging it works…

The interesting thing is that in the first few runs of the function, the function worked fine even without the debugger, but only after a few times of running the function, the problems started as I mentioned above.

I would appreciate your help, thanks

**here is the js code:
**

function getPsd() {
    sessionStorage.login = null;
    var psd = document.getElementById("password").value;
    var fullPath = 'https://localhost:44371/api/Users/Get/?psd=';
    return axios.get(fullPath + psd).then(
        (response) => {
            var result = response.data;
            if (result != null) {
                sessionStorage.login = JSON.stringify(result);
                window.location.href = '../HomePage/HomelPage.html'
            }
            return result;
        }).catch((error) => {
            alert("erorr details")
            return null;
        });
}

**html code:
**

<body dir="rtl">
    <div class="login-container">
        <section class="login" id="login">
            <header>
               
                <h4>user login</h4>
            </header>
            <form class="login-form">
                <input type="text" id="userName" class="login-input" placeholder="User" required autofocus />
                <input type="password" id="password" class="login-input" placeholder="Password" required />
                <div class="submit-container">
                    <button onclick="getPsd()" class="login-button">היכנס</button>
                </div>
            </form>
        </section>
    </div>
</body>

I tried to search for any relevant solution but i didn’t find nothing…

Vue 3 Compositions api not auto reloading when there’s a changes

I’m currently taking a lesson in vue mastery. and there’s a weird behavior. when I’m changing something in the App.vue it is auto reloading and showing my changes. But when I’m changing something in the component files, it is not auto reloading. i just follow the documentation on how to setup a vue 3 application

App.Vue

<script setup>
import ProductDisplay from '@/Components/ProductDisplay.vue'
import { ref } from 'vue'

 const cart = ref(0)
 const premium = ref(true)
</script>
<template>

<div class="nav-bar"></div>
<div class="cart">{{ cart }}</div>
<ProductDisplay :premium="premium" />

</template>

Components/ProductDisplay.vue

<script setup>
import { ref, computed } from "vue";
import socksGreen from "@/assets/images/socks_green.jpeg";
import socksBlue from "@/assets/images/socks_blue.jpeg";

const props = defineProps({
  premium: Boolean,
 });

 const details = ref(["50% cotton", "30% wool", "20% polyster"]);

 const variants = ref([
   { id: 2234, color: "green", image: socksGreen, quantity: 50 },
   { id: 2235, color: "blue", image: socksBlue, quantity: 0 },
 ]);

 const inStock = computed(() => {
   return variants.value[selectedVariants.value].quantity > 0;
 });
 const selectedVariants = ref(0);

 const cart = ref(0);

 const onClick = () => {
   cart.value += 1;
 };

 const image = computed(() => {
   return variants.value[selectedVariants.value].image;
 });
const updateVariant = (index) => {
  selectedVariants.value = index;
};

const shipping = computed(() => {
  if (props.premium) {
    return "Frees"
  } else {
    return "Out of Stock";
  }
});
</script>

<template>
 <div class="product-display">
   <div class="product-container">
     <div class="product-image">
       <img :src="image" alt="" />
     </div>
     <div class="product-info">
       <h1>{{ product }}</h1>
       <p v-if="inStock">In Stock</p>
       <p v-else>Out of Stock</p>
       <p>{{ shipping }}</p>
       <ul>
         <li v-for="detail in details">{{ detail }}</li>
       </ul>
      <div
        class="color-circle"
        v-for="(variant, i) in variants"
        :style="{ backgroundColor: variant.color }"
        @mouseover="updateVariant(i)"
      ></div>
      <button
        :class="{ disabledButton: !inStock }"
        class="button"
        @click="onClick"
        :disabled="!inStock"
      >
        Add to Cart
      </button>
     </div>
   </div>
  </div>
 </template>

How do I resolve Invalid Hook call error in React when trying to use route/navigate

I’m working on a project currently and keep getting this error with my routing:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at Object.throwInvalidHookError (react-dom.development.js:16227:1)
    at Object.useContext (react.development.js:1618:1)
    at useInRouterContext (hooks.tsx:85:1)
    at Navigate (components.tsx:196:1)
    at Login.jsx:24:1

This is the components of the app that I’ve got coded:

import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import { Navigate } from "react-router-dom";

const Login = () => {
  const location = useLocation();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const submitForm = (event) => {
    event.preventDefault();
    fetch("http://localhost:8000/users")
      .then((response) => response.json())
      .then((data) => {
        const user = data.find(
          (user) =>
            user.email &&
            user.email.toLowerCase() === email.toLowerCase() &&
            user.password &&
            user.password.toLowerCase() === password.toLowerCase()
        );
        if (user) {
          Navigate("/profile");
        } else {
          setErrorMessage("Invalid email or password");
        }
      })
      .catch((error) => console.log(error));
  };

  return (
    <div>
      <form onSubmit={submitForm}>
        <div>
          <label htmlFor="email">Enter Email Address:</label>
          <input
            type="text"
            name="email"
            id="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div>
          <label htmlFor="password">Enter Password:</label>
          <input
            type="password"
            name="password"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <button type="submit">Login</button>
      </form>
      {errorMessage && <p>{errorMessage}</p>}
    </div>
  );
};

export default Login;

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Profile from "./components/Profile";
import Login from "./components/Login";

function App() {
  return (
    <div className="wrapper">
      <h1>Application</h1>
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/profile" element={<Profile />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

import React from "react";


const Profile = () => {
  return (
    <div>
      <h2>Dashboard</h2>
      <p>Welcome to your profile page!</p>
      {/* Display user profile information here */}
    </div>
  );
};

export default Profile;

I’ve tried several fixes, such as reinstalling VSCode/Node.js, starting a new React app, using npm link ../myapp/node_modules/react… Most fixes I could find in the last 24 hours.

This is my current react versions:

PS C:UsersAdminDocumentsSD Semester2Final_Sprintfinalsprint> npm ls react
[email protected] C:UsersAdminDocumentsSD Semester2Final_Sprintfinalsprint
├─┬ @testing-library/[email protected]
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
└── [email protected]

Also, when I try and see the react version on my browser console with React.version, it says that React is not defined.

Binary array present in response is being converted to string in react

Hi I am using axios to make backend api calls. My response object which is generated using Java has following structure

 {
      workbook: [] //array of binary data of excel file generated using apache poi
      userId:<userId>
      
   }

When I receive the response given by axios , ‘workbook’ property which is supposed to be byte array is coming as string. I am not sure if axios is converting the byte array to string. Can someone tell me What is the correct way of dealing with byte data in axios

React todo app: “TypeError: t is not iterable”. What am I missing?

Building a to do app with React(vite) using useState. While trying to implement localStorage, I encountered an error where my app runs fine on the npm run dev server, but on the live commit, the form functionality is broken, and throws a TypeError:

index-b568087f.js:61 Uncaught TypeError: t is not iterable
    at o (index-b568087f.js:61:377)
    at onClick (index-b568087f.js:61:798)
    at Object.Ld (index-b568087f.js:37:9855)
    at Ad (index-b568087f.js:37:10009)
    at Id (index-b568087f.js:37:10066)
    at Ds (index-b568087f.js:37:31459)
    at Rc (index-b568087f.js:37:31876)
    at index-b568087f.js:37:36788
    at tc (index-b568087f.js:37:8967)
    at Yo (index-b568087f.js:37:33162)

This one is new to me, so any help is appreciated. Below is my App.jsx, which contains all the code for my application.

import "./App.css";

// components
import Header from "./Components/Header.jsx";
import { useState, useEffect } from "react";

function App() {
    const localList = JSON.parse(localStorage.getItem("list"));

    // state with list of todos
    const [list, setList] = useState(localList);

    useEffect(() => {
        localStorage.setItem("list", JSON.stringify(list));
    }, [list]);

    // state with input value
    const [input, setInput] = useState("");

    // function to add todos
    const addTodo = (todo) => {
        const newTodo = {
            id: Math.random(),
            todo: todo,
        };

        // add the todo to the list
        if (input !== "" && input !== " ") {
            setList([...list, newTodo]);
        }

        // clear input box
        setInput("");
    };

    const submitOnEnter = (e) => {
        e.preventDefault();
        if (e.key === "Enter") {
            if (input === "" || input === " ") {
                return;
            }
            document.getElementById("addTask").click();
        }
    };

    const deleteTodo = (id) => {
        // filter out todo with id
        const newList = list.filter((todo) => todo.id !== id);

        // set list state to be the filtered list
        setList(newList);
    };

    return (
        <>
            <div className="container">
                <Header />
                <div className="inputContainer">
                    <input
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        id="inputField"
                        onKeyUp={submitOnEnter}
                    />
                    <button id="addTask" onClick={() => addTodo(input)}>
                        Add
                    </button>
                </div>

                <ul>
                    {list?.map((todo) => (
                        <div className="todoItemContainer">
                            <li className="todoItem" key={todo.id}>
                                {todo.todo}
                            </li>
                            <button
                                className="deleteTodo"
                                onClick={() => deleteTodo(todo.id)}
                            >
                                &times;
                            </button>
                        </div>
                    ))}
                </ul>
            </div>
        </>
    );
}

export default App;

Initially, I was trying to solve a problem where .map was reading undefined. I fixed this by adding a ternary operator (list?.map) to check that list was an array.

After that, everything continued to work great on the npm run dev server, but the live commit’s functionality subsequently broke.

I’ve looked through the DevTools and am pretty sure the error is coming from calling the AddTodo() function, but I’m stumped on how to solve it. I’ve checked some other Stack Overflow posts and am having some trouble figuring this out.

Of course I can’t preview the dev server but I’ve linked the live commit below.

repo: https://github.com/noahpittman/todo-app-vite-react

commit: https://todoreact-np.netlify.app/

recursing filter array js

i have array:

[
 {id: 1, name: 'Parent1'},
 {id: 2, name: 'Child1', parent: {id: 1, name: 'Parent1'}},
 {id: 3, name: 'Child2', parent: {id: 1, name: 'Parent1'}},
 {id: 4, name: 'GrandChild1', parent: {id: 3, name: 'Child2'}},
 {id: 5, name: 'GrandChild2', parent: {id: 3, name: 'Child2'}}
]

I need to write a function with an id argument that will return an array that does not include the element with id and all of its children and children of childrens. Help pls

I tries write recursing function but fallen

How to remove child from an array of objects lengths and merge element array property

I have array of object whose element contains an array property. I need to reduce the array to shorter one based the label value and merge and replace _data array to new one like this below:

const originalArray = [
    {  label: "approved", data: [1, 0, 0, 0, 0, 0, 0] },
    {  label: "approved", data: [0, 2, 0, 0, 0, 0, 0] },
    {  label: "rejected", data: [0, 0, 3, 0, 0, 0, 0] },
    {  label: "rejected", data: [0, 0, 0, 1, 0, 0, 0] },
    {  label: "pending", data: [0, 1, 0, 0, 0, 0, 0] },
    {  label: "pending", data: [0, 0, 0, 0, 0, 7, 0] }
];
const expectedArray = [
    {  label: "approved", data: [1, 2, 0, 0, 0, 0, 0] },
    {  label: "rejected", data: [0, 0, 3, 1, 0, 0, 0] },
    {  label: "pending", data: [0, 1, 0, 0, 0, 7, 0] },
    
]

I tried to merge the data property of each element by label and then create a unique array from it

List is not being updated in React after change in child

I’ve seen plenty of similar questions, but somehow the usual answers don’t work in my case.

I have a simple list of items being loaded from an API, see screenshot. When I press the ‘Set cover’ button, I expect the items to be refreshed and the ‘Set cover’ to appear on the other item. The API cleans all cover attributes and sets it on the item that is selected.

This is the code for the list:

import React, {useEffect, useState} from "react";
import ImageItem from "./ImageItem";

export default function ImageForm({reviewId}) {

    const [items, setItems] = useState([]);

    function setCover(id) {
        const newList = items.map((item) => {
            return {
                ...item,
                cover: (item.id === id),
            };
        });

        console.log('newlist', newList);
        setItems(newList);
    }

    const loadList = () => {
        fetch("/api/review/" + reviewId + "/images")
            .then((res) => res.json())
            .then((json) => {
                console.log('useEffect', json);
                setItems(json);
            });
    }

    useEffect(() => {
        loadList();
    }, []);

    return (
        <>
            <div className="row">
                <div className="col col-sm-6">
                    {items.map((data) => {
                        return <ImageItem key={data.id}
                                          data={data}
                                          reload={loadList}
                                          makeCover2={setCover}
                        />;
                    })}
                </div>
            </div>
        </>
    );

}

And this is the code for the item Component:

And this is the code for the item Component:

import React, {useState, useRef, useEffect} from "react";
import axios from "axios";
import {Dropdown} from "react-bootstrap";

export default function ImageItem({data, remove, reload, makeCover2}) {
    const [imageData, setImageData] = useState(data);

    const makeCover = async function (item) {
        axios.post('/api/image/' + imageData.id + '/setcover').then(res => {
            if (res.data.errors) {
                console.error(res.data.errors);
            } else {
                makeCover2(imageData.id);
            }
        }).catch(err => {
            console.error(err);
        })
    }

    return (<div className="row my-2 py-2 image-item">

        <div className="col p-0 m-0">
            <div className="row">
                <div className="col">
                    <img className="img-fluid" alt="" src={'/upload/img/' + imageData.image_name}/>
                </div>
                <div className="col text-end">
                    <Dropdown>
                        <Dropdown.Toggle variant="success" id="dropdown-basic">Actions</Dropdown.Toggle>
                        <Dropdown.Menu>
                            <Dropdown.Item as="button" onClick={() => setShowForm(true)}>Change comment</Dropdown.Item>
                            {!imageData.cover && <Dropdown.Item as="button" onClick={makeCover}>Set cover</Dropdown.Item>}
                            <Dropdown.Item as="button" onClick={() => remove(imageData.id)}>Delete</Dropdown.Item>
                        </Dropdown.Menu>
                    </Dropdown>
                </div>
            </div>
        </div>
    </div>)

}


I tried 2 approaches:

  • Call a function makeCover2 that updates all items in the list after the API is done updating the rows and..
  • Call a reload function that just calls the loadList function, getting all items from the API again.

In both cases, the Set cover dropdown option stays on the same item in the list. But it should jump to the other item after clicking it. What is going on?

enter image description here

What could be the reason that two seemingly identical texts don’t match with “match“ method?

I converted and checked each character in a string to Unicode and they seemed identical but are not matching and return null.
Below is the related code:

if(editedNodeText.match(editedSource)){
   ...
  }else{
   console.log(`一致しないストリング:${editedNodeText}と${editedSource}`)
   console.log(`${convertCodeUnits(editedNodeText)}とn${convertCodeUnits(editedSource)}`)
  }
                
// Output for 2nd part:
63,61,6e,20,62,65,20,72,6f,74,61,74,65,64,20,34,35,20,64,65,67,72,65,65,73,20,6c,65,66,74,20,61,6e,64,20,72,69,67,68,74,20,28,73,65,65,20,6c,61,72,67,65,72,20,69,6d,61,67,65,29,3bと
63,61,6e,20,62,65,20,72,6f,74,61,74,65,64,20,34,35,20,64,65,67,72,65,65,73,20,6c,65,66,74,20,61,6e,64,20,72,69,67,68,74,20,28,73,65,65,20,6c,61,72,67,65,72,20,69,6d,61,67,65,29,3b

Here’s the code that’s used for conversion which I copied from a website:

function convertCodeUnits(str) {
    const codeUnits = [];
    for (let i = 0; i < str.length; i++) {
        codeUnits.push(str.charCodeAt(i).toString(16));
    }
    return codeUnits;
} 

I tried deleting zero-width spaces (which is done outside the code shown) but still doesn’t match. Am I misunderstanding something?

npm run dev isnt starting a server on localhost

I am working on a website using react.js and tailwindcss.
I wanted to see how far Ive gotten just to find out that the “npm run dev” command is not starting a server on localhost.
Does anyone know how I can reslove this issue as Ive never seen this before

I have tried running the commannd on a new project to see if it was reserved to this project or a global one. This also did not work

div.innerHTML and div.innerText behaving differently when appending

I have an asp.net web app that tails a log file. I want to insert new log entries in the bottom of a div and have it scroll updawards. If I use the following line, it works fine

textDiv.innerText += value.toString() + "rn";    

However, If I use the following, It adds new entries to the top, not the bottom.

textDiv.innerHTML += value.toString() + "rn";  

I need to be able to use innerHTML so that I can parse entries into spans, colour them etc. I have the div styling as follows

.textdiv {
    height: 800px;
    display: flex;
    overflow: auto;
    flex-direction: column-reverse;
    background-color: aliceblue;
    border-style: solid;
    border-width: 2px;
    padding: 10px;
    border-radius: 10px;
}

See image blow of the div in action. Can anyone help me to correct the behaviour of textDiv.innerHTML such that new entries into the div are added to the bottom not the top. Many thanks.

enter image description here

Why does the php file not open when i click button second time?

const baseUrl = "components/data.php";

function loadData(requestType, containerSelector, limitVal, offsetVal) {
  const container = document.querySelector(containerSelector);

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      container.innerHTML = xhr.responseText;
    }
  };
  xhr.open(
    "POST",
    `${baseUrl}?requestType=${requestType}&limit=${limitVal}&offset=${offsetVal}`,
    true
  );
  xhr.send();
}

const eventsBtn = document.getElementById("events");
eventsBtn.addEventListener("click", function () {
  console.log("Loading events");
  loadData("getEvents", ".events-container", 5, 0);
});

const feedBtn = document.querySelector("#feed");
feedBtn.addEventListener("click", function () {
  console.log("Loading posts");
  loadData("getPosts", ".feed", 5, 0);
});

here is the code which is calling content from php file using js

When i try to call the function 2nd time using any button, the file path is changing and i am getting 404 error, on first click the function always read right content but on 2nd time the url is wrong

for example its changing from components/data.php to /components/data.php

TypeORM: Many to Many Relation outputs wrong data with where

I have 2 tables, User and Race. Race can contain multiple Users, so I created a Many to Many Relation. I need to get all Races where a user is member of. Now the problem is, that it doesn’t get all users but only the user requesting.

If I remove the relations: ["users"] from the find method, it works as expected.

Entities

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({unique: true})
  email: string;
}
@Entity()
export class Race {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @ManyToMany(() => User, {onDelete: "CASCADE"})
  @JoinTable()
  users: User[];
}
export default class RaceRepository {
  public async listRaces(user: number): Promise<Race[]> {
    return await this.entityHandler
      .getRepository(Race)
      .find({where: {users: {id: user}}, relations: ["users"]});
  }
}

Expected Output

[
  {
    "id": 1,
    "name": "Race 1",
    "users": [
      {
        "id": 1,
        "email": "[email protected]"
      },
      {
        "id": 2,
        "email": "[email protected]"
      }
    ]
  }
]

Actual Output

[
  {
    "id": 1,
    "name": "Race 1",
    "users": [
      {
        "id": 1,
        "email": "[email protected]"
      }
    ]
  }
]