how to use usestate with node.js backend and react frontend

i use node.js in my HTML file using tag now how do i use useState with it
I tried:

const {useState} = React

Here is my code

const {useState} = React;
function App(){
const {text, setText} = useState("Hello world")
console.log(text);
function handleClick(){
  setText("Hello universe")
}

return <h1 onClick={handleClick}> {text} </h1>
}

ReactDOM.render(<App />, document.getElementById('root'))

Is there a way to return all successful promises from fetch until one fails?

The Javascript function Promise.allSettled waits for all resolved or rejected promises to finish. Promise.all won’t return the resolved promises if any of them are rejected, and Promise.race and Promise.any only give the first settled or fufilled promise.

Is there a way to send off multiple promises (say 100), and then as soon as one fails (perhaps have 20 succeed) cancel the unsettled promises (of which there are 100 – 20 – 1 = 79 not yet settled)? I don’t even need the details of which failed, but just a sort of Promise.someSettled function.

Is that possible?

How do I insert data from a table to a form

I have a form which I want to be auto-completed with data from a table I made. How can I achieve this?
This is my table:

    while($row  = mysqli_fetch_assoc($result))
    {
        echo "<tr>";
        echo "<td>" . $row['ID_Angajati'] . "</td>";
        echo "<td>" . $row['Nume'] . "</td>";
        echo "<td>" . $row['Prenume'] . "</td>";
        echo "<td>" . $row['CNP'] . "</td>";
        echo "<td>" . $row['Data_Nasterii'] . "</td>";
        echo "<td>" . $row['Sex'] . "</td>";
        echo "<td>" . $row['Numar_Telefon'] . "</td>";
        echo "<td>" . $row['Salariu'] . "</td>";
        echo "<td class = container_update ><button type = 'button' onclick = 'yes_js_modal();'>Update</a></td>";
        echo "<td class = container_delete ><a href = 'includes/delete.php?id=$row[ID_Angajati]'>&times;</a></td>";
        echo "</tr>";
    }
    echo "</table>";

And this is my form:

<form action="" method="POST">
<table align="center">

<tr>
<td>ID_Angajati:</td>
<td><input type = "text" name="ids" required></td>
</tr>

<tr>
<td>Nume:</td>
<td><input type = "text" name="nume" required></td>
</tr>

<tr>
<td>Prenume:</td>
<td><input type = "text" name="prenume" required></td>
</tr>

<tr>
<td>CNP:</td>
<td><input type = "text" name="cnp" required></td>
</tr>

<tr>
<td>Data Nasterii:</td>
<td><input type = "text" name="data" required></td>
</tr>

<tr>
<td>Sex:</td>
<td><input type = "text" name="sex" required></td>
</tr>

<tr>
<td>Numar Telefon:</td>
<td><input type = "text" name="nr_telf" required></td>
</tr>

<tr>
<td>Salariu:</td>
<td><input type = "text" name="sal" required></td>
</tr>

<tr>
<td colspan = "2" align = "center">
<input type="submit" id="button" name="submit" value="Update Details"></a>
</td>
</tr>

</table>
</form>

I want for instance ID_Angajati from my form to be auto-completed in the form with the value of one of my rows in the table. This will happen when I click on the “Update” button from the table.

IntersectionObserverAPI Return to default state when none of the elements are visible

I’m using a React Hook to detect when an element is visible in the viewport. Until then, everything works fine but I need to ‘reset’ the state when everything is hidden (like reaching the footer or the header).

Here’s my hook:

import { useState, useEffect, useRef } from 'react'

const useIntersect = (ref) => {
  const [isOnScreen, setIsOnScreen] = useState(false)
  const observerRef = useRef(null)

  useEffect(() => {
    observerRef.current = new IntersectionObserver(([entry]) => {
      setIsOnScreen(entry.isIntersecting)
    })
  }, [])

  useEffect(() => {
    observerRef.current.observe(ref.current)
    return () => observerRef.current.disconnect()
  }, [ref])

  return isOnScreen
}

export default useIntersect

And here’s the state I’m updating:

  const elementRef = useRef(null)
  const[state, setState] = useState('nothing is visible')
  const onScreen = useIntersect(elementRef)

  useEffect(() => {
    return onScreen ? setState('an item is visible') : null
  })

  return (
    <Item ref={elementRef}>
      ...
    </Item>
  )

I need to be able to say setState('...') to something (let’s say a string) when all the elements are off the viewport (when the condition onScreen is not met) but even when I reach the footer when nothing is visible, it keeps the last item in memory.

I’ve tried many things but I cannot figure a way out πŸ™

Thanks for the help!

Is there any way to insert latex in a JavaScript quiz web-app

I am creating a JavaScript web app in which questions.js is a file from which questions are being fetched. Now i need to insert math equation in the questions and for that i am using Latex but the problem is that only the first time the script tag latex loads and if being clicked to next button the equation in the next question cannot been seen please help.

Here are some SS :
When Loaded First Time:
enter image description here

When Loaded For The Next Time :
enter image description here

This same goes on for the rest of questions



const quiz = [
    {
        q:'Which Month Comes Right Before June? \(\frac{-b \pm \sqrt{b^2-4ac}}{2a}\)',
        options:['may','september','july','august'],
        answer:0
    },
    {
        q:'Which Month Comes Right After Febrary? \(\frac{-b \pm \sqrt{b^2-4ac}}{2a}\)',
        options:['may','september','july','march'],
        answer:3
    },
    {
        q:'Which Month Comes Right Before November? \(\frac{-b \pm \sqrt{b^2-4ac}}{2a}\)',
        options:['may','october','july','august'],
        answer:1
    },
    {
        q:'Which Month Comes Right Before January? \(\frac{-b \pm \sqrt{b^2-4ac}}{2a}\)',
        options:['december','september','july','august'],
        answer:0
    },
    {
        q:'Which Month Comes Right Before March?',
        options:['december','febrary','july','august'],
        answer:0
    }
]

For Latex I Am using Hostmath : https://www.hostmath.com/Math/MathJax.js?config=OK

What is the difference between these two codes (Javascript)?

I am new to javascript and I am Confused between these 2 codes.
Can someone tell me what’s the difference between these 2 codes, They both work exactly the same so which one should I use?
THANK YOU:)



    const calcAverage = (a, b, c) => ((a + b + c) / 3);
console.log(calcAverage(44, 23, 71))

function chechWinner(avgDolphins, avgKoalas) {
    if (avgDolphins >= 2 * avgKoalas) {
        return `Dolphins win (${avgDolphins} vs ${avgKoalas})`;
    } else if (avgKoalas >= 2 * avgDolphins) {
        return `Koalas win (${avgKoalas} vs ${avgDolphins})`;
    } else {
        return "No team wins.";
    }
}
console.log(chechWinner(scoreDolphins, scoreKoalas));

**AND**
function chechWinner(avgDolphins, avgKoalas) {
    if (avgDolphins >= 2 * avgKoalas) {
        console.log(`Dolphins win (${avgDolphins} vs ${avgKoalas})`);
    } else if (avgKoalas >= 2 * avgDolphins) {
        console.log(`Koalas win (${avgKoalas} vs ${avgDolphins})`);
    } else {
        console.log("No team wins.");
    }
}
chechWinner(scoreDolphins, scoreKoalas);

Bind a View to my Fetch Call from antoher Controller Ui5

Hi when I call this function in my file ResultDevice.controller.js it loads the devices perfectly in the ResultDevice.view.xml. Now I want to call the function in my BaseController,because I have multiple Controllers & Views and need to acess them, but my View is not builded. I dont have a Error Code, when I paste console.log under this.getView it returns my Call. So I think he cant connect to “aribadevices” from the BaseController.js in the ResultDevice.view.xml file. I tried to paste id=”idView1″ in the this.getView(“idView1”) but then I get an error that he cant find the View “idView1”

Please Help me xd…

the Base Controller Function:

onCompletedNotebook: function (oEvent) {
            const tabletUrl = '/api/tablets?limit=1000&offset=0';

            fetch(tabletUrl).then(res => res.json()).then(res => {
                const dataModel = new JSONModel();
                dataModel.setData({
                    items: res
                });
                this.getView().setModel(dataModel, "aribadevices")
            })
        }, 

``` The View from ResultDevice.view.xml: ```

<mvc:View id="idView1" controllerName="TESTE.TESTE.controller.ResultDevice" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
    xmlns:card="sap.f.cards" xmlns:f="sap.f">
    <App>
        <pages>
            <Page title="ResultDevice" showNavButton="true" navButtonPress="oNavButton_press">
                <content>
                    <List items="{aribadevices>/items/results}">
                        <items>
                            <CustomListItem class="list">
                                <f:Card class="sapUiMediumMargin" width="300px">
                                    <f:header>
                                        <card:Header title="{aribadevices>name}"/>
                                    </f:header>
                                    <f:content>
                                        <Text text="{aribadevices>name}"/>
                                    </f:content>
                                </f:Card>
                            </CustomListItem>
                        </items>
                    </List>
                </content>
            </Page>
        </pages>
    </App>
</mvc:View>

how can i get redirected from component to another by using a button

i’m trying to get redirected from a component to another using a onClick in a button and yet i tried a lot of things nothing works
last thing i tried was the useHistory and push but maybe i’m using it wrong i don’t know the prooblem so here’s the code i tried

import React from 'react';
import { NavLink } from 'react-router-dom';
import"./home.css";
import { useHistory } from 'react-router-dom';

const Home = () => {
{/*this is where i called my useHistory object*/}
const history = useHistory();
return (
<React.Fragment>
    <nav className="navbar navbar-expand-lg ">
         <div className="container-fluid">
            <i className="fas fa-paw fa-2x"></i>
            <NavLink className="navbar-brand " to="/" >Pets Forever</NavLink>
            <div className="collapse navbar-collapse justify-content-end" id="navbarNav">
                <ul className="navbar-nav mr-auto"> 
                    <li className="nav-item" >
                        <NavLink className="nav-link" to="/about">About Us</NavLink>
                    
                    </li>
                    <li className="nav-item">
                        <NavLink className="nav-link" to="/contact">Contact Us</NavLink>

                    </li>
                     
                    <li className="nav-item">
                        <NavLink className="nav-link" to="/login">Login</NavLink>

                    </li>
                    <li className="nav-item">
                        <NavLink className="nav-link" to="/signUp">Sign Up</NavLink>
                    </li>
            
                </ul>
            </div>
        </div>
    </nav>

   <div className="head-div">
            <h1>Hi there!</h1>
            <h1>Do you want buy me a toy?</h1>
            <br/>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat, quia?</p>
            <p>Excepturi atque possimus quas qui temporibus ratione</p>  
            <button type="button" className="btn btn-warning" onClick={()=>{this.history.push("/login") }
 }>Shop Now</button>
    


        </div> 
</React.Fragment> 

);
}

export default Home;

How do I get my error message to go away after form validation in react js?

I have a simple login form that intakes user email and user password, the goal is to have an error message pop up directly under the input field, as well as add a red border around the input only if it’s left blank or the pattern is wrong. Only one of my input fields is performing properly. (The input fields seem to be dependent of each other? )Any help would be appreciated !

The other input field is getting the red border removed once the password meets the requirements however, the error message remains. The goal is to have both the red border removed and the error message removed, Here’s a screenshot:

enter image description here

class Login extends Component {
  constructor(props) {
    super(props);

    this.emailInput = React.createRef();
    this.passwordInput = React.createRef();

    this.state = {
      email: "",
      password: "",
      emailError: false,
      passwordError: false,
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.validate = this.validate.bind(this);
  }

  handleInputChange(e) {
    const { value, name } = e.target;
    this.setState({ [name]: value });
    console.log(value);
  }

  validateEmail(userEmail) {
    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
    return emailPattern.test(userEmail);
  }

  validatePassword(userPassword) {
    const passwordPattern =
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;
    return passwordPattern.test(userPassword);
  }

  styleBorderEmail(emailInput, styles) {
    this.emailInput.current.style.border = styles;
  }

  styleBorderPassword(passwordInput, styles) {
    this.passwordInput.current.style.border = styles;
  }

  validate() {
    let emailError = this.email;
    let passwordError = this.password;

    if (!this.validateEmail(this.state.email)) {
      emailError = "email not valid";
      this.styleBorderEmail(this.emailInput, "1px solid red");
    } else {
      this.styleBorderEmail(this.emailInput, "1px solid black");
    }
    if (!this.validatePassword(this.state.password)) {
      passwordError = "password not valid";
      this.styleBorderPassword(this.passwordInput, "1px solid red");
    } else {
      this.styleBorderPassword(this.passwordInput, "1px solid black");
    }
    if (emailError || passwordError) {
      this.setState({ emailError, passwordError });
      return false;
    }
    return true;
  }

  handleSubmit(e) {
    e.preventDefault();
    const isValid = this.validate();

    if (isValid) {
      alert("successful submit");

      // clears the form after it's been submitted
      this.setState({
        email: "",
        password: "",
        emailError: false,
        passwordError: false,
      });
    }
  }

  render() {
    return (
      <div className="login-component">
        <div className="login-container">
          <h2>Welcome Back!</h2>
          <br />
          <form onSubmit={this.handleSubmit}>
            <div className="login-group">
              <label htmlFor="email" className="login-label">
                Your email
              </label>
              <input
                className="login-input"
                type="text"
                name="email"
                id="email"
                placeholder="Enter your email"
                value={this.state.email}
                onChange={this.handleInputChange}
                onKeyUp={this.validate}
                ref={this.emailInput}
              />
              {this.state.emailError && (
                <span className="error-login">
                  Please enter a valid email address
                </span>
              )}
            </div>
            <div className="login-group">
              <label htmlFor="password" className="login-label">
                Password
              </label>
              <input
                className="login-input"
                type="password"
                name="password"
                id="password"
                placeholder="Enter your password"
                value={this.state.password}
                onChange={this.handleInputChange}
                onKeyUp={this.validate}
                ref={this.passwordInput}
              />
              {this.state.passwordError && (
                <span className="error-login">Please enter a password</span>
              )}
            </div>
            <div>
              <button type="submit" className="login-btn">
                Login
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Login;

How do I make js EventListener work properly? [closed]

I’ve got a problem with a website, when I attach a js function to a button using code
html:

<button id="myid" type="submit">run</button>

js:

document.getElementById("myid").addEventListener("click", myFunction, false);
async function myFunction() {}

it is not working, but when I use
html:

<button id="myid" type="submit" onclick="myFunction()">run</button>

js:

async function myFunction() {}

it is all good. How do I make first code snippet working?
p.s. system windows 10, browser Firefox of latest version

NodeJS setInterval() running parallel to loop using async [duplicate]

I have two functions

  1. console.log() running every second, using setInterval()
  2. a constant loop calculating (eg. repeatedly calculating sha256)

Using asynchronous JavaScript, how can I run both a constant loop and still console.log() every second.

Everything I’ve tried brought no solution, as the calculating loop always goes to the top of JavaScript’s queue and runs until it I manually stop this loop and then the interval starts going every second

I know that a solution also involves Web Workers, but I would rather like to understand this first.

How to access an Object’s values using arr.reduce()

I am trying to achieve the below:

var arr = [
 {name: 'width', value: 10}, 
 {name: 'height', value: 20}, 
]

arr.reduce((ack, item)=>{
  ack.width = item.value
  ack.height = item.value
  return ack
},{})

//Expected output:

{width: 10, height: 20}

//Actual output:

{width: 20, height: 20}

Maybe I don’t understand how .reduce() works a 100%?

Thanks in advance for your help

How parse React tsv to table

ΠŸΠΎΠ΄ΡΠΊΠ°ΠΆΠΈΡ‚Π΅, ΠΊΠ°ΠΊ ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠ°Ρ€ΡΠΈΡ‚ΡŒ Ρ„Π°ΠΉΠ» TSV Ρ‚Π°ΠΊ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ Π½Π° Π²Ρ‹Ρ…ΠΎΠ΄Π΅ Π±Ρ‹Π»Π° Ρ‚Π°Π±Π»ΠΈΡ†Π° Ρ‚ΠΈΠΏΠ° Exel с Π΄Π°Π½Π½Ρ‹ΠΌΠΈ

import React, { useContext } from "react";
import {FileContext} from 'gitea-react-toolkit';
import { CsvToHtmlTable } from 'react-csv-to-table';


const ErrorTable = () => {
  
  const {state: file} = useContext(FileContext);
  

  return (
    <div className="item ErrorTable">
      {file?.content || 'ErrorTable'}
      <CsvToHtmlTable
  data={file?.content}
  csvDelimiter="  "
  tableClassName="table table-striped table-hover"
/>     
    </div>
  );
};

export default ErrorTable

enter image description here