JavaScript splice function deletes the item and all the next items

Greetings I have a simple JS CRUD project where I am adding users to array and store the array in the local storage, and I have a function to delete the users, every user row in the table have including button with onclick event that calls the function and giving it the user index

And in the function I get the index and call the splice function to delete just one item starting from the index

But when I delete an item it deletes the item and all the next items and I get this error in my console Uncaught RangeError: Maximum call stack size exceeded

The add user function

$('#addUserBtn').click(function (e) {
    e.preventDefault();

    let user = {
        no: $('#userNoInput').val(),
        name: $('#userNameInput').val(),
        email: $('#userEmailInput').val(),
        tel: $('#userTelInput').val(),
        dob: $('#userDobInput').val(),
        rmk: $('#userRmkInput').val(),
    }

    usersContainer.push(user);

    localStorage.setItem('myUsers', JSON.stringify(usersContainer));
    displayUsers();
    //clearForm();
});

the displayUsers() function

function displayUsers() {
let markUp = ``;

for (let i = 0; i < usersContainer.length; i++) {
    markUp += `<tr><td>${usersContainer[i].no}</td><td>${usersContainer[i].name}</td>
<td>${usersContainer[i].email}</td><td>${usersContainer[i].tel}</td><td>${usersContainer[i].dob}</td><td>${usersContainer[i].rmk}</td><td><button class="btn btn-danger" onclick="onclick(deleteUser(${i}))"><i class="fas fa-trash-alt"></i></button></td></tr>`;
    }

    $('#tableBody').html(markUp);
}

The delete function

function deleteUser(index) {
    usersContainer.splice(index, 1);
    localStorage.setItem('myUsers', JSON.stringify(usersContainer));
    displayUsers();
}

Website scrolls up automatically when clicked on input box only in android mobile phones

I developed a website using React and added a contact form at the end. When the website is viewed in android mobile phones, there is a bug. If user clicks on any input box or text area, website automatically scrolls up.
I have not added any link or anchor tag to input boxes still it behaves unexpectedly. I searched on the issue and it is something related to bug in android native browser, the page resizes when it tries to open soft keyboard. I don’t face the same issue when site is being viewed on Laptop or ios devices.

Here’s link to the website:
https://dronzer03.github.io/athang-portfolio/

Code:

                <div>
                  <h4>Leave me a message or feedback:</h4>
                </div>
                <div className="form">
                  <div>
                    <label>Name:</label>
                  </div>
                  <div>
                    <input id="name" value={from} onChange={changeFrom} onFocus={onFocusChange} />
                  </div>
                  <div>
                    <label>Email:</label>
                  </div>
                  <div>
                    <input id="mail" value={email} onChange={changeEmail} />
                  </div>
                  <div>
                    <label>Message/Feedback:</label>
                  </div>
                  <div>
                    <textarea id="msg" value={msg} onChange={changeMsg} />
                  </div>
                  <div>
                    <Button className="btns" onClick={sendMail}>
                      Send
                    </Button>
                  </div>
                </div>
              </div>

combine two half images of logo

is there anyone who can help me in combining 2 half images of the logo (3D objects) into a single logo? & text became fadein/slide-in when logo split on hover effect.

here is the code

<body>
    <!-- section 3 start -->
    <div class="container-fluid ">
  <div class="row" id="sec3">
    <div class="col text-white services"> 
        <h1>Our Services</h1> <br>
        <h4>Buy & Sell </h4>
            <p style="margin-left: 0%;">Discover the new opportunities and <br>
                a new path towards success.</p> <br> 
<h4>Rental</h4>
<p style="margin-left: 0%;">Discover the new opportunities and a new <br>
path towards success</p><br>

<h4>Property Management</h4>
<p style="margin-left: 0%;">Discover the new opportunities and a new path <br>
towards success</p> <br>

<h4>Investment management</h4>
<p style="margin-left: 0%;">Discover the new opportunities <br>
and a new path towards success.</p> <br>

<h4>Real Estate Advice</h4>
<p style="margin-left: 0%;" id="fifth_text">Discover the new opportunities and a new <br>
path towards success</p>
    </div>

    <div class="col" id="aSide"><model-viewer src="images/Split_logo.glb" alt="Baksh Logo" ios-src="images/Split_logo.glb"></model-viewer></div>



</div> 
</div> 

<!-- section 3 end -->
</body>
</html>

Javascript update a JSON data depending on key

I have a simple array and I want to update this array with the value order:"asc" and want to delete all other order key only if type == "user" and key == "country"

const items = [
    {
        type: "user",
        values: [
            {order:"asc", key:"first_name"},
            {key:"last_name"},
            {key:"address"},
            {key:"country"},
        ]
    },
]

My expected result is

const items = [
    {
        type: "user",
        values: [
            {key:"first_name"},
            {key:"last_name"},
            {key:"address"},
            {order:"asc", key:"country"},
        ]
    },
]

I’m able to do this with map inside map. Is it possible without looping twice?

items.map(
    x => { if (x.type == "user") {
        x.values = x.values.map(y => {
            if (y.key.includes("country")) {
                y.order = "asc"
            } else if (JSON.stringify(x.values).includes("country")) {
                delete y.order
            }
            return y
        })
    }
    return [x]
});

Auto-Showing browser input calendar/clock when date/time field is clicked

I have a form that has a few date and time input types on it. During feedback sessions, many users of the form didn’t know the helper icons at the end of the input fields showed a calendar or time picker. Also, the vast majority of those users would strongly prefer to use those instead of manually typing data in.

I’d like to make those fields show the calendar/time selector when one of those fields gets focus instead of just when you click on the helper at the end of the textbox.

I’ve seen a few questions about this but most seem outdated or require some extra javascript library. Is there a way, with just plain CSS and/or javascript, to trigger the calendar/timepicker to show when a user clicks in the input field?

Nuxt-auth custom refresh controller

Our backend refresh API needs 2 parameters: the grant_type & the refresh_token. The nuxt-auth v5 does support refresh token but the default handleRefresh() does not allow custom parameters as far as I can see – if this can be tweaked, that would also be great.

As a workaround, I tried creating a custom scheme + custom refresh controller. This is my code until now:

// nuxt.config.js

auth: {
  strategies: {
    local: {
      scheme: '~/schemes/refresh_token.js',
      token: {
        property: 'token',
        global: true,
        type: 'Bearer'
      },
      refreshToken: {
        property: 'refresh_token',
        data: 'refresh_token',
        maxAge: 60 * 60 * 24 * 30
      },
      endpoints: {
        login: { url: '/api/v1/login', method: 'post', propertyName: 'data.token' },
        user: { url: '/api/v1/profile', method: 'get', propertyName: '' },
        refresh: { url: '/api/v1/token', method: 'post' }
      }
    }
  }
}
// schemes/refresh_token.js

import { RefreshScheme } from '@nuxtjs/auth-next';
import RefreshTokenController from './controllers/refresh_token';

export default class RefreshTokenScheme extends RefreshScheme {
  constructor ($auth, options) {
    super($auth, options);
    this.refreshController = new RefreshTokenController(this);
  }
}
// schemes/controllers/refresh_token.js

import { RefreshController } from "@nuxtjs/auth-next";

export default class RefreshTokenController extends RefreshController {
  handleRefresh() {
    console.log('custom handle refresh');
  }
}

Right now, I have this error:
Class extends value undefined is not a constructor or null at the export default class RefreshTokenController extends RefreshController line.

Also, my console says:
This dependency was not found: * fs in ./node_modules/@nuxtjs/auth-next/dist/module.js, ./node_modules/hasha/index.js

Event shift key in combination

I need undo and redo in javascript.

ctrl + z = undo

ctrl + shift + z = redo

In the code described below, undo works normally but redo does not work. I noticed if it is shift.key alon then it works, if combined with others (shift.key + ctrl.key or “z”) it doesn’t work. Why.., or am I wrong somewhere in the code?

function isKeyPressedUndo(event) {
  var x = document.getElementById("demo");
  if (event.ctrlKey && event.key === 'z') {
    x.innerHTML = "The UNDO key was pressed!";
  } else {
    x.innerHTML = "The UNDO key was NOT pressed!";
  }
}

function isKeyPressedRedo(event) {
  var x = document.getElementById("demo");
  if (event.shiftKey && event.ctrlKey && event.key === 'z') {
    x.innerHTML += "The REDO key was pressed!";
  } else {
    x.innerHTML += "The REDO key was NOT pressed!";
  }
}
<input type="text" onkeydown="isKeyPressedUndo(event), isKeyPressedRedo(event)">

<p id="demo"></p>

Multiple sticky headers

Is there another way I can get multiple sticky headers to stack under each other than setting the top offset as the height of the previous sticky headers?

In the code snippet if I set top: 50px in .inner-header it works fine but I am looking for some other solution.

.container {
  overflow: auto;
  height: 300px
}

.header {
  height: 50px;
  background-color: pink;
  position: sticky;
  top: 0;
  z-index: 1;
}

.content {
  height: 1000px;
}

.section {
  height: 150px;
  border: 1px solid black;
  margin-top: 40px;
}

.inner-header {
  height: 30px;
  border-bottom: 1px solid black;
  position: sticky;
  top: 0;
  background-color: gray;
}
<div class="container">
  <div class="header">
    Main sticky header
  </div>
  <div class="content"> 
    <div class="section">
      <div class="inner-header">
        Section sticky header
      </div>
    </div>
  </div>
</div>

Java Script to get todays date in HTML date field

I want to display my date in HTML input type=”date” in dd/mm/yyyy format

My Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript getDate</h2>

<input type="date" id="demo" name="rwrkDate" required="true" >

<script>
const d = new Date();
var date=d.getDate();
var month=d.getMonth();
var year=d.getFullYear();
var today=date+'/'+month+'/'+year;
document.getElementById("demo").value = today;
</script>

</body>
</html> 

I get the date field with mm/dd/yyyy only and does not display the date. Secondly how do I get previous date if some checks are implemented.

How to download file in Js?

I am making an api call to export excel file and api is returning the response as encrypted string like,

PK-[Content_Types].xmlµSËnÂ0ü•È×*6ôPUCÇ©ô{“Xø%¯¡ð÷]8”R‰
qòcfgfWöd¶q¶ZCB|ÃÆ|Ä*ð*h㻆},^ê{Va–^K<4lÈfÓÉb+ªõذ>çø ªœD"xBÚœÌtLˆR-eâv4º*ø>×¹h°éä  Z¹²¹zÜÝé†É­Q2S,±öúH´Þòvà`o"ÞUÏRÙµC(2q†Ãqa9SÝ
& ........... goes on .......

So the above response needs to be converted into downloadable excel file.

For which I have used the following code,

const outputFilename = `${Date.now()}.xls`;
const url = URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', outputFilename);
document.body.appendChild(link);
link.click();

It generate an excel file but when I open the file, it says that the file format is unsupported.

Could you please help me with steps to convert the response data into an real downloadable excel file without issues?

I am using reactjs app for the implementation

Thanks in advance.

NextJS: Firebase Firestore setDoc running twice – TypeScript

I am trying to add some dummy data to firebase firestore but only the setDoc command is running twice. I don’t quite understand what I’m doing wrong. This is only a .ts file, not a component file & the function is not running twice. I am sure of that. Below is my code:

import { collection, setDoc, Timestamp, doc, addDoc } from "firebase/firestore";
import { db } from "./clientApp";

type MyBrand = { name: String; image: String; dateAdded: Timestamp };
var brandCollRef = collection(db, "brand");

async function addBrands() {
    let brands: Array<MyBrand> = [];

    for (var i = 1; i <= 10; i++) {
        var myItem = {
            name: `Brand ${i}`,
            image: `https://picsum.photos/1024/1024?random=${i}`,
            dateAdded: Timestamp.now(),
        };
        brands.push(myItem);
        console.log("Added Item: " + myItem.name);
    }

    brands.forEach(async (item) => {
        // New Doc created
        const newDoc = doc(brandCollRef);
        console.log("New Doc Created: " + newDoc.id);

    // This code is running twice
        await setDoc(newDoc, item);
        console.log("Set Data in: " + newDoc.id);
    });
}

export { addBrands };

Please let me know what I’m doing wrong.

NodeJS- How to turn JSON data from a GET request into a javascript variable?

On my express server, I have this POST function that takes parsed data lines from raspberry Pis and writes them on a postgresql database, every minute or so.

I have a lot of algorithms that run on the rPi and make calculations with these data lines but I would like to migrate all the calculation to the server side and have the algorithms located on the same machine as my Express code.

So the same POST function that inserts data into the sql database would push the raw data to my program as js variables that I can call in functions. However, I do not know the proper syntax to do this? Or would there be a simpler way to do this?

Thanks!

Here is my code:

router.post("/", async (req, res) => {
  try {
    const {name, position1, position2, batt_lvl} = req.body
    const newPosition = await pool.query(
      "INSERT INTO position (name, position1, position2 batt_lvl) VALUES ($1, $2, $3, $4) RETURNING *",
      [name, position1, position2, batt_lvl])
      res.json(newPosition.rows[0]);
  } catch (err) {
      console.error(err.message)
    }
})
  
router.get("/", async (req, res) => {
  try {
    const allPositions = await pool.query("SELECT * FROM positions");
    res.json(allPositions.rows)
  } catch (err) {
      console.error(err.message)
    }
})

JS weird += result [duplicate]

I used this function to add 5 to a number in a p element:

function add5() {lifeTotal.textContent += 5;}

I have a similar function that subtracts 5 to that same number:

function minus5() {lifeTotal.textContent -= 5;}

Now my problem is that while the subtracting function works as expected, the adding one just puts 5 at the right side of the number. So if the number was 10, it would return 105, as if both numbers were actually strings and not numbers… while the subtracting function works normally and treats numbers as numbers…

It turns me crazy. I just learnt this += thing and I really don’t think I used it wrong…

So my solution is to instead use ++ five times, like so:

function add5() {lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++;}

It works, but it seems to me this is not the shortest way to write this.

The app I am writing is adding or subtracting by calling the corresponding function with an onclick=”function()” in html button tags.

What is happening? What is the shortest way to write this?

Thanks!

not able to set proper values into state in react

tempData.map(i =>
      selectedLine = {
        "LineItemID": i.LineItemId,
        "ReconTemplateTypeID": i.ReconTemplateTypeId
      }
    )

this.setState({ selectObject: [...this.state.selectObject, selectedLine] }, 
              function () { this.checkMultipleSelectedFlag() })

tempData contains data out of which, I want to store lineitemid and templateid in a variable and then setState into the state object. I tried writing this.setState inside map function but it is throwing error. Any idea how can i achieve this?

Why ViewPropTypes throws an error after updating the Expo SDK to 42 version?

Hello I am new to react native and I am having a problem. I am working on a mobile app. Expo recently stopped supporting 40 SDK and I had to update it to 42. After that, the application got the following error.

Unable to resolve module react-native-collapsible/config from D:Programmingmessenger3sellengage-mobilesrccomponentsAccordionindex.js: react-native-collapsible/config could not be found within the project.

Here is the code (Accordion component)

import React from 'react';
import {View, Animated} from 'react-native';
import Collapsible from 'react-native-collapsible';
import {ListItem, List} from 'native-base';
import PropTypes from 'prop-types';
import {ViewPropTypes} from 'react-native-collapsible/config';

const COLLAPSIBLE_PROPS = Object.keys(Collapsible.propTypes);
const VIEW_PROPS = Object.keys(ViewPropTypes);
const CUSTOM_PROPS = Object.keys({
  ListFooterComponent: '',
  contentContainerStyle: '',
  onScroll: '',
  onMomentumScrollEnd: '',
  overScrollMode: '',
  onEndReached: '',
  onEndReachedThreshold: '',
  refreshControl: '',
  scrollEventThrottle: '',
});

If I remove import ViewPropTypes from react-native-collapsible/config and import it from react-native the following error appears

TypeError: undefined is not an object (evaluating 'Object.keys(_reactNativeCollapsible.default.propTypes)')

Stack trace:
  node_modulesreact-nativeLibrariesLogBoxLogBox.js:148:8 in registerError
  node_modulesreact-nativeLibrariesLogBoxLogBox.js:59:8 in errorImpl
  node_modulesreact-nativeLibrariesLogBoxLogBox.js:33:4 in console.error
  node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
  node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException
  node_modulesreact-nativeLibrariesCoreExceptionsManager.js:171:19 in handleException
  node_modulesreact-nativeLibrariesCoresetUpErrorHandling.js:24:6 in handleError
  node_modulesexpo-error-recoverybuildErrorRecovery.fx.js:12:21 in ErrorUtils.setGlobalHandler$argument_0
  node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
  node_modulesregenerator-runtimeruntime.js:294:29 in invoke
  node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
  node_modulesregenerator-runtimeruntime.js:155:27 in invoke
  node_modulesregenerator-runtimeruntime.js:165:18 in PromiseImpl.resolve.then$argument_0
  node_modulesreact-nativenode_modulespromisesetimmediatecore.js:37:13 in tryCallOne
  node_modulesreact-nativenode_modulespromisesetimmediatecore.js:123:24 in setImmediate$argument_0
  node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:130:14 in _callTimer
  node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:181:14 in _callImmediatesPass
  node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:441:30 in callImmediates
  node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:387:6 in __callImmediates
  node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:135:6 in __guard$argument_0
  node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:364:10 in __guard
  node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:134:4 in flushedQueue
  [native code]:null in flushedQueue
  [native code]:null in invokeCallbackAndReturnFlushedQueue

I didn’t create this project from scratch, initially another person worked on it. I can only assume that with the update to the new version, some functionality is outdated. I tried reinstalling node_modules, clearing the cache and downgrading versions, but nothing worked. Please help me to solve this issue.

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "builda": "expo build:android"
  },
  "dependencies": {
    "@react-native-community/datetimepicker": "3.5.2",
    "@react-native-community/netinfo": "6.0.0",
    "@react-navigation/bottom-tabs": "^5.11.2",
    "@react-navigation/drawer": "^5.11.4",
    "@react-navigation/native": "^5.8.10",
    "@react-navigation/stack": "^5.12.8",
    "array-flat-polyfill": "^1.0.1",
    "axios": "^0.21.0",
    "chroma-js": "^2.1.2",
    "date-fns": "^2.27.0",
    "expo": "^42.0.0",
    "expo-app-loading": "1.1.2",
    "expo-camera": "~11.2.2",
    "expo-constants": "~11.0.1",
    "expo-document-picker": "~9.2.4",
    "expo-file-system": "~11.1.3",
    "expo-font": "~9.2.1",
    "expo-image-manipulator": "~9.2.2",
    "expo-image-picker": "~10.2.2",
    "expo-intent-launcher": "~9.1.0",
    "expo-media-library": "~12.1.2",
    "expo-notifications": "~0.12.3",
    "expo-permissions": "~12.1.1",
    "expo-secure-store": "~10.2.0",
    "expo-splash-screen": "~0.11.2",
    "expo-status-bar": "~1.0.4",
    "expo-updates": "~0.8.2",
    "expo-web-browser": "~9.2.0",
    "moment": "^2.29.1",
    "moment-timezone": "^0.5.32",
    "native-base": "^2.15.2",
    "prop-types": "^15.7.2",
    "react": "16.13.1",
    "react-content-loader": "^5.1.4",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-42.0.0.tar.gz",
    "react-native-collapsible": "^1.6.0",
    "react-native-collapsible-header-views": "^1.1.2",
    "react-native-dimension": "^1.0.6",
    "react-native-dropdown-picker": "^5.2.3",
    "react-native-elements": "^3.4.2",
    "react-native-gesture-handler": "~1.10.2",
    "react-native-gifted-chat": "^0.16.3",
    "react-native-image-modal": "^1.0.16",
    "react-native-inset-shadow": "^1.0.3",
    "react-native-ionicons": "^4.6.5",
    "react-native-keyboard-spacer": "^0.4.1",
    "react-native-modalize": "^2.0.8",
    "react-native-multi-selectbox": "^1.5.0",
    "react-native-multiple-select": "^0.5.7",
    "react-native-paper": "^4.7.2",
    "react-native-reanimated": "~2.2.0",
    "react-native-safe-area-context": "3.2.0",
    "react-native-screens": "~3.4.0",
    "react-native-svg": "12.1.1",
    "react-native-tab-view": "^2.15.2",
    "react-native-text-avatar": "^1.0.7",
    "react-native-typing-animation": "^0.1.7",
    "react-native-vector-icons": "^9.0.0",
    "react-native-walkthrough-tooltip": "1.1.11",
    "react-native-web": "~0.13.12",
    "react-native-webview": "11.6.2",
    "rgb-hex": "^4.0.0",
    "string-to-color": "^2.2.2",
    "typescript": "~4.0.0"
  },
  "devDependencies": {
    "@babel/core": "~7.9.0",
    "@expo/vector-icons": "^12.0.0",
    "@types/react-native": "~0.63.2",
    "babel-jest": "~25.2.6",
    "jest": "~25.2.6",
    "react-test-renderer": "~16.13.1"
  },
  "jest": {
    "preset": "react-native"
  },
  "lint-staged": {
    "*.{ts,tsx,js,jsx,json,md}": [
      "prettier --write"
    ],
    "*.{ts,tsx}": [
      "eslint --fix"
    ]
  },
  "private": true
}