How maltiple value using usestate localstorage in react?

I want to work using maltiple values in use state and crud in local storage use state like
const [Data,setData]=[[{
name:’luis’,
pass:’1234′,
//…….
}]
]

And it updates with the form
<input>

// …….

if value true  Display  take look at this example I try but I cannot do how to solve it

import ‘./App.css’;
import React, { useState,useEffect } from ‘react’;

function App() {
  const [User, setUser] = useState([
    {
      Name:'',
      Pass:'',
      Email:'',
    }
  ]);

 
  const [storedUser,setstoredUser]=useState([])

  
  const handle = () => {

     localStorage.setItem(JSON.stringfy(...User))
    
     setstoredUser(...User);

  };
  const remove = () => {
     localStorage.removeItem();

  };
  return (
    <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            name='Name'
            value={User.Name}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            name="Pass"
            placeholder="Password"
            value={User.Pass}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
           <h1>Email of the user:</h1>
          <input
            type="mail"
            name="Email"
            placeholder="Email"
            value={User.Email}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {storedUser.Name && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {storedUser.Pass && (
            <div>
               Password: <p>{localStorage.getItem('Pass')}</p>
            </div>
         )}
          {storedUser.Email && (
            <div>
               Password: <p>{localStorage.getItem('Email')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   ); 
}

export default App;

Here I try how to do this formate I try to all data in state and stringify set this local storage. then remove and display I think explaine on detail

Disable browser reload option using javascript or Jquery

Hi I have the following code for disabling F5

$(document).ready(function(){

 $(window).keydown(function(event){
 if(event.keyCode == 116)
 {
 event.preventDefault();
 return false;
 }
 });

});

But i am unable to resolve to prevent the browser reload.

I am trying to find the solution for disabling the browser reload. And learn in the process.

Unable to set innerHTML from HTML Collection

I have below div tag from material UI which is getting autogenerated through MUI –

<div class="MuiAvatar-root.MuiAvatar-circular.MuiAvatar-colorDefault">Some Text</div>

Through javascript , I am fetching this element as –

var ele=document.getElementByClassName("MuiAvatar-root MuiAvatar-circular MuiAvatar-colorDefault");
console.log(ele);

In console log I am able to see element with all its properties including innerHTML as Some Text

When I am trying to change the InnerHTML by –

ele[0].innerHTML="Changed Text" , I am not able to see that text got changed.

Also , before this , when I try to log innerHTML –

console.log(ele[0].innerHTML) , I am getting blank result.

How can I change the inner HTML from HTML Collection I am fetching ?

TypeScript each() as an Arrow function

I have the following TypeScript function:

$.each($("[data-static-map-image]"), function () {
    $(this).attr("src", $(this).data("mapImageUrl"));
});

I would like to convert this into an Arrow function. Unfortunately, I can’t figure out how to make it work with the each loop. Can someone give me a hint?

P.S. I ask for your indulgence as I am still in the beginning of the learning phase.

Ajax: Asyncronous Calls in Javascript to JAVA

I currently have a few basic question with asyncronous calls in JS.

I have searched and found a similar question posted in the past here:

Parallel Ajax Calls in Javascript/jQuery

But i still have some doubts about asyncronous calls.

  1. Let´s say that i make it asyncronous using a Jquery when to join both flows when both ajax calls are finished. What would happen if one of the Ajax calls fail?

  2. Some of the calls that i need to make should be asyncronous only in some cases. It´s good practice to make the type of call (asyncronous true or false) variable? or it doesn´t really matter to have an asyncronous true call when there is only one JS flow.

  3. If i need to do a few BBDD calls with my asyncronous methods (different tables). Could i have a conflict if i make two bbdd calls at the same time because i make my ajax asyncronous? i am quite a newbie with asyncronous calls. (SQL database) (Springboot Java 8)

The basic flow would be something like this:

Basic flow img

Thanks for your attention.

Onclick feature on the action button to slide the slidebar

Below application has sidebar open by default. Is there a way to make it close by default and slide when the user clicks on “Release” button.
So when the user clicks again on teh button, the side bar should slide inside and this is on and off type. Can we achieve this

library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(plotOutput("plot1", height = 250)),
      
      box(
        title = "Controls",
        sliderInput("slider", "Number of observations:", 1, 100, 50)
      ),
      box(actionButton("release", "Release"))
    )
  )
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider)]
    hist(data)
  })
}

shinyApp(ui, server)

Mongoose error of buffering timed out after 1000ms

I am learning MERN stack and currently following this tutorial.

  • I have connected with MongoDB database success fully.
    error

MongooseError: Operation users.findOne() buffering timed out after 10000ms
at Timeout.

What I have tried so far,

  • I have changed the node version to 16.
  • I have checked that my mongoDB database has access to all IP addresses.
  • I have tried to convert my router.post("/signup", (req, res)) router to asyn-await.
    But no luck was found.
    -Below is my code
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const User = mongoose.model("User");

router.get("/", (req, res) => {
  res.send("Hi new");
});

router.post("/signup", (req, res) => {
  const { name, email, password } = req.body;
  if (!email || !password || !name) {
    res.status(422).json({ error: "Please provide all data" });
  }
  User.findOne({ email: email })
    .then((isUserExist) => {
      if (isUserExist) {
        return res.status(422).json({ error: "User already exist" });
      }
      // creating an user object to story it in database
      const user = new User({
        name, 
        email,
        password,
      });
      user
        .save()
        .then((user) => {
          res.json({ message: "User has been registered successfully.." });
        })
        .catch((err) => {
          console.log("Something went wrong", err);
        });
    })
    .catch((err) => {
      console.log("Something went wrong", err);
    });
});
module.exports = router;

Mongodb connection code

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const { MONGOURI } = require("./keys");
const port = 8080;
require("../models/user");
app.use(express.json());
app.use(require("../routes/auth"));
mongoose.connect(MONGOURI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
mongoose.connection.on("connected", () => {
  console.log("Keep going....");
});
mongoose.connection.on("error", (err) => {
  console.log("Oh no error:", err);
});
app.listen(port, () => {
  console.log("GAME ON");
});

  • Below is a screenshot showing keep going... message before giving an error.
    Console screenshot

Autocomplete external library dependencies

I made an external component library using vite.

  1. design-system-lib (vite)
  2. main-package (webpack v6)

I have been downloading design-system-lib from main-pacakge as a GitHub NPM package.
There is no problem with the operation.
However, auto-completion does not work when loading from main-package.

enter image description here

The github repository address is: https://github.com/kim-doan/wdyj-design-system-web

How can I use autocomplete in an external library?

Toggle Function Logic for If Statement to send to Form Javascript [duplicate]

I am trying to toggle between if statements to show a button and add an object to a “roles” array. This is not using State at the moment. If I could use state possibly how would I implement it? Again I am updating an array in a form not to the state itself because these roles are individual objects in one array.

I am able to remove one of the buttons and objects but when I try to add the other object back on the conditional, I receive the first array again causing a duplicate. What exactly am I doing wrong here with my logic?

js.component

 const roleUUID = profile.roles[0].uuid
const roleLabId = profile.roles[0].labId

if (form.roles[0].name === 'First Program User') {
  setForm({
    ...form,
    roles: [...form.roles, { roleId: '3', name: 'First Program User', uuid: roleUUID, labId: roleLabId, labTypeId: '1' }]
  })
}

if (profile.roles[0].name === 'Program User') {
  setForm({
    ...form,
    roles: [...form.roles, { roleId: '2', name: 'Second Program User', uuid: roleUUID, labId: roleLabId, labTypeId: '2'  }]
  })
}

console.log('added form roles =>>> ', form.roles)

Advice for internal npm packages pulled into git repo

we’re working through a setup at my work and I want to see if anyone has any advice/best practices for what we’re doing here.

We have code in a git repo for our ui library that produces an npm package (in an internal private registry). That package then gets pulled into the git repos for each of the main products. The question is about versioning the package.

Because we’re going from a parallel dev process (git) to linear package versions, which then gets pulled back into another parallel dev process (product git repos), there’s an opportunity for code from the library to be accidentally released to production:

  • Change A is made to the library, produces v1.0
  • Change B is made to the library, produces v1.1
  • The library version in a product is updated to v1.1 to access Change B
  • Product change, and v1.1, is released; Change A in v1.0 is accidentally included

Does anyone have any advice, best practices, or alternate workflows we could keep in mind? The main thing is, we want the UI library stored in one repo but able to be pulled into multiple other repos.

Thank you!

Merge collection instantly and make a new collection with grouping

Currently using MongoDB Atlas for a Timesheet system. I have 4 collection in it.

  1. category (Has the record of clock in types and staff roles )
  2. employees ( Has the record of the staff name and a unique pin )
  3. timesheets ( Has the record of a Pin with the clock in type and date and time )
  4. users ( Admin login details )

Data of employees is as follows:

{
"_id": {
    "$oid": "62cf98457"
},
"name": "Name Test",
"pin": "1234",
"role": "Sales",
"site": "Port Melbourne",
"email": "[email protected]",
"phone": "999 999 999",
"dob": "2022-07-10",
}

Data of timesheet is as follows:

{
"_id": {
    "$oid": "62cf98e47caaa2ac70fba490"
},
"pin": "1234",
"type": "in",
"date": "18-01-2022",
"time": "Tuesday, January 18, 2022 6:25 AM",
"image": "image file url"
},{
"_id": {
    "$oid": "62cf98e47caaa2ac70fba490"
},
"pin": "1234",
"type": "out",
"date": "18-01-2022",
"time": "Tuesday, January 18, 2022 4:25 PM",
"image": "image file url"
}

For now I am querying the employees collection if pin exits or not and if it does filtiring in the timesheets collection which has same pin values again filtiring them by date and then by types with time to get all employees timesheets details is a list with date.

This process is taking long for a querry.

Can we directly create a new collections example employees_timesheets which will group user details and create an object inside filtering dates from timesheets collection. Example:

{
"_id": {
    "$oid": "62"
},
"name": "Name Test",
"pin": "1234",
"role": "Sales",
"date": "18-01-2022",
{
"18-01-2022":  [{
       "type": "in",
       "time": "Tuesday, January 18, 2022 6:25 AM",
       "image": "image file url"
  },{
       "type": "out",
       "time": "Tuesday, January 18, 2022 4:25 AM",
       "image": "image file url"
  }]
 }
}

What is this.props.children for React error boundaries returned when there is no error?

I understand that a higher component can pass props in between open and closing tags of a functional component that it will render. In react error boundary component this.props.children is being returned to the component that its wrapping (App.js). What is this.props.children thats is being returned if there is no error?

        if (this.state.hasError){
            return <h1>{this.state.errorMessage}</h1>;
        }else {
            return this.props.children;
        }

         
    }```

NameRanges Appscript no headers in array

I am trying to get in an array the range name of the GSheet inside appscript, however, it puts inside the array all the complete namerange, for example, to get only the data and not the headers.

I tried with .offset(), do you know any other way?

This is what I did:

var id = SpreadsheetApp.getActive().getRangeByName('id').offset(1,0).getValues();

However, when I do this even if I don’t get the header, I still get an array with the size as if I had the header.

TypeError: o is not a function only on production

I have a Laravel app with webpack and a lot of dependencies that works perfectly on dev, so in the server if I run yarn dev with the APP_ENV set to dev, it works without issues; but in the same server if I set the APP_ENV to production and run yarn production it just throws this error:

TypeError: o is not a function

And I cannot debug that because the Javascript file is compressed with Webpack and I don’t know what is that “o”.

Is there any way to debug that or do anyone know why can a script work on dev environment but not on production?

Why is my navbar rendering twice in React? (Router)

I’m currently learning react and am trying develop a personal website. I tried making the home page the index which worked, but now the navigation bar is rendering twice. Any idea on how to stop this?

import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import About from "./pages/About";
import Projects from "./pages/Projects";
import NoPage from "./pages/NoPage";
import './App.css';

    function App() {
      return (
        <div className="App">
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<Layout />}>
                <Route index element={<Home />} />
                <Route path="About" element={<About />} />
                <Route path="Projects" element={<Projects />} />
                <Route path="*" element={<NoPage />} />
              </Route>
            </Routes>
          </BrowserRouter>
        </div>
      );
    }
    
    export default App;

Example of what I mean