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

Responsiveness/@media query’s…. Im currently learning so go easy on me and my code. :D

Hey so this is my first post/question, im currently learning HTML/CSS/JAVA looking to find a job in the new year.
ive been asked to make a site for someone (code is linked below) what im struggling with is the media query/responsiveness for my banner image, it wont scale down when i go to tablet or phone screen.
any feedback on my code is welcome too as i said i am learning still so be nice 😀
thank you in advance Andrew

@import url('https://fonts.googleapis.com/css?family=poppins:200,300,400,500,600,700,800,900&display=swap');
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Open Sans', sans-serif;
}
body {
    background: rgb(17, 17, 17);
    min-height: 200vh;
}
header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: 0.4s;
    padding: 40px 100px;
    z-index: 100000;
}
header.sticky {
    padding: 5px 100px;
    background: #fff;
}
header .logo {
    position: relative;
    font-weight: 400;
    color: #fff;
    text-decoration: none;
    font-size: 3em;
    letter-spacing: 2px;
    transition: 0.6s;
    font-family: 'Barlow', sans-serif;
}
header .logo:hover {
    color: rgb(24, 24, 24);
}
header ul {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}
header ul li {
    position: relative;
    list-style: none;
}
header ul li a {
    position: relative;
    margin: 0 15px;
    text-decoration: none;
    color: #fff;
    letter-spacing: 2px;
    font-weight: 500px;
    transition: 0.6s;
    font-size: 23px;
    font-family: 'Barlow', sans-serif;
}
header ul li a:hover {
    color: rgb(24, 24, 24);
}
.banner {
    position: relative;
    width: 100%;
    height: 100vh;
    background: url(images/banner.jpg);
    background-size: cover;
    opacity: .4;
}
header.sticky .logo, header.sticky ul li a {
    color:#000
}
.h1 {
color: rgb(255, 255, 255);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
width: 80%;
padding: 20px;
text-align: center;
font-size: 60px;
}

.image1 {
    margin-top: 10px;
    margin-left: 10px;
    border-radius: 19px;
}

/* about me */
.about {
    width: 100%;
    padding: 78px 0px;
    background-color: #191919;
}
.about img {
    height: 800px;
    width: 520px;
    padding-left: 12px;
}
@media (max-device-width: 500px) {
    .about img {
        padding-right: 20px;
        height: 500px;
    }
}
.about-text {
    width: 550px;
}
.main {
    width: 1130px;
    max-width: 95%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.about-text h1 {
    color: #fff;
    font-size: 80px;
    text-transform: capitalize;
    margin-bottom: 20px
}
.about-text h5 {
    color: #fff;
    font-size: 25px;
    text-transform: capitalize;
    margin-bottom: 25px;
    letter-spacing: 2px;
}
.about-text p {
    color: #fcfc;
    letter-spacing: 1px;
    line-height: 28px;
    font-size: 18px;
    margin-bottom: 45px;
}
button {
   background: #f9004d;
   color: #fff;
   text-decoration: none;
   border: 2px solid transparent;
   font-weight: bold;
   padding: 13px 30px;
   border-radius: 30px;
}
button:hover {
    background: transparent;
    border: 2px solid #f9004d;
    cursor: pointer;
}
.name {
    font-size: 30px;
    color: #fcfc;
    letter-spacing: 5px;
}



/* footer */
footer {
    height: auto;
    width: 100vw;
    font-family: "poppins";
    padding-top: 40px;
    color: #fff;
    background: rgb(17, 17, 17);

}
.footer-content {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    text-align: center;
}
.footer-content h3 {
    font-size: 1.8rem;
    font-weight: 400;
    text-transform: capitalize;
    line-height: 3rem;
}
.footer-content p {
    max-width: 500px;
    margin: 10px auto;
    line-height: 28px;
    font-size: 14px;
}
.socials {
    list-style: none;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 1rem 0 3rem 0;
}
.socials li {
    margin: 0 10px;
}
.socials a {
    text-decoration: none;
    color: #fff;
}
.socials a i {
    font-size: 1.1rem;
    transition: color .4s ease;
}
.socials a:hover i {
    color: #000;
}
.footer-bottom {
   width: 100%;
   padding: 20px 0;
   background: #000;
   text-align: center;
}
.footer-bottom p {
    font-size: 14px;
    word-spacing: 2px;
    text-transform: capitalize;
}
.footer-bottom span {
    text-transform: uppercase;
    opacity: .4;
    font-weight: 200;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>enDURANCE FIT, Andrea Durance Personal Trainer</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css">
</head>
<body>
  <div>
   <header>
     <a href="#" class="logo">enDurancefit</a>
     <ul>
       <li><a href="#">Home</a></li>
       <li><a href="#aboutme">About Me</a></li>
       <li><a href="#">Services</a></li>
       <li><a href="#">Testimonies</a></li>
       <li><a href="#">Contact Me</a></li>
     </ul>
   </header>
   <section class="banner">
   </section>
   <h1 class="h1">Welcome To enDurance fit <p style ="font-family: Rajdhani">Andrea Durance</p><p>Personal Trainer</p> </h1>
  </div>


  <!--Section 2: About me-->
<section class="about" id="aboutme">
  <div class="main">
    <img src="images/profile.jpg">
   <div class="about-text">
     <h1>About Me</h1>
     <h5>Personal Trainer <span style="color: #f9004d;"> & Fitness Instructor</span></h5>
     <p>I have 5 years’ experience within the fitness industry, firstly as a level 2 fitness instructor, then a level 3 personal trainer, also teaching various classes along the way, including spin, kettlebells and bootcamps. 
      My passion for fitness began in my early teens around the age of 13-14.
      <p> This is where my aspirations to become a personal trainer began, and not long after that is when my career began. The manager of the gym where I was training at the time recognised my passion and offered me work experience, which led on to an apprenticeship in which I gained my fitness instructing qualification. Leading on from this I completed my level 3 personal training through a different apprenticeship based at another gym.</p>
      <p>A funny fact about the name of my company ‘enDurancefit’, is that I first came up with it when I was about 14, and I was dead set that one day I will have a personal training business and I wanted it to be called enDurancefit, and here we are! Moral of the story, if you have a goal, stick at it and don’t lose sight of it no matter the setbacks you may encounter! </p>
      <p>Training and exercise not only keeps me physically well, but mentally well also. One of the many reasons I love it, one of my aims is to help my clients keep physically and mentally well with a combination of positive coaching and lifestyle changes. 
      <p>Training and exercise is more than just the physical results, of course seeing muscle growth/fat loss/weight gain or loss depending on the goal is always something to be proud of. But for most people training becomes their ‘me’ time, time to forget life’s stresses and a time to focus on you, your goals and your own health and wellbeing.
      I want to help my clients reach a happy, healthy, and sustainable lifestyle, training to their maximum capabilities and smashing goals set, also whilst enjoying life.</p> 
      <p>FITTER, HEALTHIER, STRONGER, AND HAPPIER. 
      enDurancefit <br>
      <div class="name" > ANDREA DURANCE </div> 
      </p>
      <button type="button">Contact Me</button>
   </div>
  </div>
</section>














<section>
 <footer class="footer-content">
      <div>
        <h3>enDurancefit</h3>
        <p>Thank you for visiting, dont forget to check out my socials.</p>
        <ul class="socials">
          <li><a href="#"><i class="fab fa-facebook-square"></i></a></li>
          <li><a href="#"><i class="fab fa-twitter-square"></i></a></li>
          <li><a href="#"><i class="fab fa-youtube-square"></i></a></li>
        </ul>
      </div>
      <div class="footer-bottom">
        <p>Copyright &copy;2021 enDurance fit. designed by <span>Andrew Hinkley</span></p>
      </div>
 </footer>
</section>

</body>


<!--Scripts-->
<!--Script for nav bar-->
<script type="text/javascript">
  window.addEventListener("scroll", function(){
    var header = document.querySelector("header");
    header.classList.toggle("sticky", window.scrollY > 0);
  })
</script>
<!--Scrip End-->


</html>

React how to show xml view with expand and collapse functions? (react-xml-viewer)

Hi I wanted to show xml view in my application. To achieve that I was using react-xml-viewer but also I wanted to add all expand and collapse functions aswell when I check react-xml-viewer I couldn’t see it. Is there any way to achieve this with react-xml-viewer or is there any package that I can use. Both solution is ok for me.

import React from 'react';
import XMLParser from "react-xml-parser";
import * as s from './XMLDetail.styles';
import XMLViewer from "react-xml-viewer";

const XMLDetail = props => {
const {
    isDarkMode = false,
    appHdrData = "",
    documentData = "",
    isOpenButton=false,
} = props;

//Return
return (
    <div>
        <s.ColumnContainer>
            <s.Customlabel isOpenButton={isOpenButton} >Header</s.Customlabel>
            <s.Customlabel isOpenButton={isOpenButton} >Document</s.Customlabel>
        </s.ColumnContainer>
        <s.XMLDetailContainer>
            <s.XMLContainer isOpenButton={isOpenButton}>
                <XMLViewer xml={appHdrData}/>
            </s.XMLContainer>
            <s.XMLContainer  isOpenButton={isOpenButton}>
                <XMLViewer xml={documentData}/>
            </s.XMLContainer>
        </s.XMLDetailContainer>
    </div>
)

}

export default XMLDetail

TypeError: jwt.sign is not a function help guys

generateToken.js

    const jwt = require('jsonwebtoken');
  const generateToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: '30d'
});
 };
  module.exports = generateToken;

userController.js

 const asyncHandler = require('express-async-handler')
 const User = require("../Models/userModal");
 const generateToken = require('../utils/generateToken');




const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;

const user = await User.findOne({ email });

if (user && (await user.matchPassword(password))) {
    res.json({
        _id: user._id,
        name: user.name,
        email: user.email,
        token: generateToken(user._id),
    });
  } else {
    res.status(401);
    throw new Error("Invalid Email or Password");
}
});


 const registerUser = asyncHandler(async (req, res) => {
const { name, email, password, } = req.body;

const userExists = await User.findOne({ email });

if (userExists) {
    res.status(404);
    throw new Error("User already exists");
}

const user = await User.create({
    name,
    email,
    password,
});

if (user) {
    res.status(201).json({
        _id: user._id,
        name: user.name,
        email: user.email,
        token: generateToken(user._id),
    });
 } else {
    res.status(400);
    throw new Error("User not found");
}
});

module.exports = { registerUser, authUser }

userModel

const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')

const userSchema = mongoose.Schema(
 {
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: [true, 'The email is unique']

    },
    password: {
        type: String,
        required: true
    },
  }
);
userSchema.pre('save', async function (next) {
if (this.isModified('password')) {
    next();
}
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
 });
 userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};

const User = mongoose.model('user', userSchema);
module.exports = User;

.env

JWT_SECRET:'piyush1234'

And here’s the error in postman

{

TypeError: jwt.sign is not a function
   at generateToken (C:UsersYassine JedidiDesktopprojet alaserverutilsgenerateToken.js:3:16)
   at C:UsersYassine JedidiDesktopprojet alaserverControllersuserControllers.js:50:20
   at runMicrotasks (<anonymous>)
   at processTicksAndRejections (internal/process/task_queues.js:93:5)

}

How access Response in Express outside Route controller

I am using Express JS for backend API.

I need to simply use res object from custom service, not route controller.

Of course I am calling service function from controller and I know that I can easily pass res as an argument and access it, but I wonder if there is other case or maybe better practice.

const videoaskResponse = async (req, res, next) => {
  try {
    await webhookService.handleVideoaskResponse(req.body, res)

    res.status(200).json({ received: true })
  } catch (error) {
    next(error)
  }
}

Here’s example how I handle that case.

Cannot convert undefined or null to object in Next.js

Hey I am building a login page with Next.js and next-auth
I have also written in providers array in [...nextauth].js.

But when I run the code

import { getProviders, signIn } from "next-auth/react";

function Login({ providers }) {
  return (
    <div className="bg-black min-h-screen w-full flex justify-center items-center flex-col ">
      <img className="w-48 mb-5" src="/spot-it-aye.png" alt="" />

      {Object.values(providers).map((provider) => (
        <div key={provider.name}>
          <button
            className="bg-green-500 p-4 rounded-full hover:rounded-lg"
            onClick={() => signIn(provider.id, { callbackUrl: "/" })}>
            Login With {provider.name}
          </button>
        </div>
      ))}
    </div>
  );
}

export default Login;

export async function getServerSideProps() {
  let providers = await getProviders();

  return {
    props: {
      providers,
    },
  };
}

I get the

Unhandled Runtime Error

TypeError: Cannot convert undefined or null to object.

Any help would be appreciated.image

React Native app not showing information on Android from App.js

I got a problem.

I create a notification system in my react-native app to unify the design on Android and iOS.

So I implement the system in App.js and directly in RootContainer like that :

App.js

render () {
  return (
    <Provider store={context.store}>
      <RootContainer />
    </Provider>
  )
}

RootContainer

render() {
    return (
        <StyleProvider style={getTheme(material)}>
            <View style={styles.applicationView}>
                <NotificationToast 
                    message={this.props.infoNotif}
                    onTimeOut={() => this.props.initialDeleteInfoNotif()}
                />
                <StatusBar barStyle='light-content' />
                <ReduxNavigation />
            </View>
        </StyleProvider>
    )
}

So, the NotificationToast is my notification system. He will find this.props.infoNotif from my Redux.

In iOS, everything work perfectly, but on Android, anything happens.

And I don’t know why.