Change object parameter by useState() in ReactJS

So I’m trying to change an object parameter that is being called by .map inside a curly braces. Here is the code:

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

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])
  
  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{`value.location.${searchQuery}`}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;

But it doesn’t work, it only return a string. I’ve tried to :

  1. Remove the Apostrophe ``
  2. Change the curly braces to another brackets []
  3. Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces
  4. Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

Import JS and CSS files into the JSP file, and the browser console prompts 404

I imported JS and CSS files in the head part of the JSP file. However, some JS and CSS files prompt 404 errors. My < head > section is as follows:
enter image description here

The prompt in the browser console is as follows
enter image description here

It can be seen that the “/ Editor” directory is missing in the prompted error
But when I modify other JS and CSS paths, the same error will be prompted

enter image description here

enter image description here

These files are in the “editor” directory. I have also tried to restart idea. Clearing the browser cache and restarting the computer have no effect. Hope to get an answer

typescript extend new property without modifying existing type

I have this code

type VehicleDetails = {made: string}

function doSomethingWithVehicleDetails (details: VehicleDetails) { //what to add here for newProperty?
  console.log(details);
}

doSomethingWithVehicleDetails({ made: '123', newProperty: true })

https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/FDAuE8AcFMAIDVoAsCWBjANtAItUBDFDAZ1gF5YBvAW3wBNoAuWY0AJxQDsBzAXxABmAV05pQKAPadYdCQGUJ1PKh4B1FKCSJUmHHkIlYACgYEixZtvRZcZkgEoqsAPTOA7knyhYoCbHp0sEjQbHACEmywnNBuAApsEjBsEAD8wLCwaFLEElgAdBgS3Cb65vYA3MD8wLIKSppc3OqaVrq2BsRGlLC0DMwA5ACMAEwAzP0ANFEx8YkhEMzsQnC89kA

without modifying type VehicleDetails = {made: string}, how can I add newProperty in doSomethingWithVehicleDetails argument to fix the error?

ERR_UNKNOWN_FILE_EXTENSION NodeJS

I am trying to import the @metamask/detect-provider” library but when I go to run npm start I get the error ERR_UNKNOWN_FILE_EXTENSION.
I tried searching online for a possible solution but was unsuccessful

Source code app.js

import detectEthereumProvider from '@metamask/detect-provider';

const provider = await detectEthereumProvider();
const express = require("express");
const app = express();


if (provider) {
    app.get("/", function (req, res) {
        res.sendFile(__dirname + "/index.html");
    });
} else {
    app.get("/", function (req, res) {
        res.sendFile(__dirname + "/error.html");
    });
}

module.exports = app;

package.json

{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "type": "module",
  "dependencies": {
    "@maticnetwork/maticjs": "^3.2.2",
    "@maticnetwork/maticjs-web3": "^1.0.1",
    "@metamask/detect-provider": "^1.2.0",
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1",
    "request": "^2.88.2",
    "truffle": "^5.4.33",
    "web3": "^1.7.0"
  }
}

JavaScript parseInt not working with “10”?

I wrote the function that tokenizes arithmetic string expression into an array of tokens, such as numbers and operators. Everything’s fine but I get a weird results when dealing wuth strings containing “10”. Here’s the code:

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (parseInt(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [1, '0', NaN, '-', 3] ??

For now I can’t come up with an idea, why this happens.

Display second prompt if the first prompt is not TRUE

I have a problem when i try to display new prompt, i use loop but it will display both my prompt. Here is my code and i really need help

<body>
<p id="age" style="font-weight: bold"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
var age = document.getElementById("age").value;
var age = prompt("Enter Your birth year:");// This is the first prompt 
const year = new Date().getFullYear();
if (age != null) { 
          document.getElementById("age").innerHTML =
            "Your " + age + " is so beautiful"; // If user enter birth year < current year will display this
        }
  do {
     age = prompt("Re-enter your birth year:"); // Ortherwise, this will display and they need to enter until birth year < current year
    } while (age > year && age != null);
        var tuoi = year - age;// This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
        document.getElementById("age").innerHTML =
          "Tuổi " + tuoi + " này đẹp đó";
}
</script>
</body>

How to import css file of react-datepicker into SSR written in Nestjs and AdminJS?

I am using the react-datapicker inside of SSR project written in Nest.js and Admin.js. I need to add some React components so I need to import import ‘react-datepicker/dist/react-datepicker.css’ into the project so that should work properly with proper design. The error is says [Nest] 93478 – 02/12/2022, 12:47:22 PM ERROR [ExceptionsHandler] Unexpected character ‘@’ (Note that you need plugins to import files that are not JavaScript). I could not find any solution specific to my problem. Is there anyone can help me to solve this issue?

How to send a request to Nodejs backend server when the client closes the browser tab or window?

I am trying to build an application where whenever the client closes the browser window/tab I should send a notification to the backend to destroy the logged-in session and log the details of the running session. I have tried onbeforeunload but it is not working as intended, as it also executes on page reload. Also, it does not send the request by closing the browser tab.

why I cant see any output on my reactjs app?

I have started my first React lesson but I cant see any output on my localhost(3000), will you pls help me ?

this is my JS code :

import React from 'react';
import ReactDOM from 'react';

const element = React.createElement("div", { id: "title", className: "app-title" }, "this is a test text");

ReactDOM.render(element, document.getElementById("root"));

Randomize assigned colors in an array in p5.js

I have been trying to recreate one of Vera Molnar’s paintings, and to add a twist, I wanted to randomize the colors in the array as I drag my mouse over the canvas. However, I cannot for the life of me figure out how to do this. Below is one of many attempts at this. What could I be doing wrong?

As for the colors, the intial order of the colors is something I would like to keep, as it is directly mimicking the original painting, but as the mouse is moved into the canvas/frame, i want to trigger the random colors.

Thank you for your help!

https://editor.p5js.org/k-yr-k/sketches/vU7cTZ8Ra

// recreating Lent mouvement bleu, orange, rouge et noir, 1955, by Vera Molnar

const width = 700;
const height = 700;

let radius = 58;
let len = 8;
let color;
let colors;

function setup() {
  createCanvas(width, height);

  colors = [
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#e2592f",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#000000",
    "#000000",
    "#9bd6ff",
  ];
}

function draw() {
  background(255);

  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      let x = i * 80;
      let y = j * 80;
      color = colors.shift();
      if (color === undefined) {
        color = "white";
      }
      fill(color);
      noStroke();
      ellipse(y + 65, x + 65, radius);
    }
  }

  noLoop();
}

function mouseDragged() {
  color = random(colors);
}

React-Hook Form: Cannot read properties of undefined (reading ‘field’)

My form is a nested one and if I’ll only submit one product, there are no errors, But If I’ll click Add More Product and click the button to add more colors this is the error that I’m getting:

Cannot read properties of undefined (reading 'field')

This is where it pointed out:

<input
  36 |   name={`test[${nestIndex}].nestedArray[${k}].color`}
  37 |   ref={register({ required: true })}
> 38 |   defaultValue={item.field}
     |                     ^
  39 |   style={{ marginRight: "25px" }}
  40 | />

and here:

return (
  19 |   <div>
> 20 |     {fields.map((item, k) => {
     |            ^
  21 |       return (
  22 |         <div key={item.id} style={{ marginLeft: 20 }}>
  23 |           <label>{k + 1}</label>

Adding more products, and adding more colors will make these errors appear

This is what the form looks like:

enter image description here

Codesandbox link: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

The error is in the fieldArray.js:

i

mport React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].nestedArray[${index}].product`}
                inputRef={register({ required: true })}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}

How to hide Input fields if $GET_() is empty? [closed]

Good day experts!

I’m having trouble hiding the input fields if &_GET(N) method is empty without deleting its php code. Here’s the code below:

<html>
<body>
<?php echo $_GET["subject"]; ?><br><br>
<?php echo $_GET["instruction"]; ?><br><br>
<?php echo '<input type="text">' ; echo $_GET["new_1"]; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_2"] ; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_3"] ; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_4"] ; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_5"] ; ?><br>
</body>
</html> 

react-native-dropdown-picker How to show 2 information in 1 item

I am using React-Native-Dropdown-Picker to do a list of products, then I have trouble wanting to display information as at the bottom, which means I want to show both information in 1 Item as at the bottom of the picture

The images

I searched as well as reviewing the Props of React-Native-Dropdown-Picker, but I still haven’t found the answer

Hope everyone can help me

Thanks

Using a CancelToken with an axios instance

I’ve read several similar questions, but I’m still struggling to be able to cancel my requests given my code structure.

On clicking one of the following elements I’d like to be able to cancel all other requests except the new one, however it seems to cancel all requests, and then prevents axios making any new ones. I’m new to cancelling tokens, so don’t really know what I’m doing wrong here:

import {cancelTokenSource} from 'API';

let isActiveRequest;

document.body.addEventListener('click', async(e) => {
    const userElement = e.target.closest('.user-element');
    const appElement = e.target.closest('.app-element');


    if(isActiveRequest) {
        cancelTokenSource.cancel();
        isActiveRequest = false;
    }

    if(userElement) {
        isActiveRequest = true;
        try{
            const users = await Admin.getUsers();
            isActiveRequest = false;
            // display users
        } catch(err) { isActiveRequest = false; }
    }
    if(appElement) {
        isActiveRequest = true;
        try{
            const applications = await Admin.getApplications();
            isActiveRequest = false;
            // display applications
        } catch(err) { isActiveRequest = false; }
    }
});

API.js

export const cancelTokenSource = axios.CancelToken.source();

export default axios.create({
    baseURL: 'http://localhost:8080',
    cancelToken: cancelTokenSource.token
});

Admin.js

export default class Admin {
  
    getUsers({index, limit, orderField, orderDirection}) {
        return API.get('/admin/applicants', { params: { index, limit, orderField, orderDirection } });
    }
    getApplications({index, limit, orderField, orderDirection}) {
        return JRS.get('/admin/applications', { params: { index, limit, orderField, orderDirection} });

    ...
}

Thanks

Get value from input field and insert in URL Javascript

I have a form on wordpress, I need to get a value from a field and pass it into this script. This is what I’ve managed to do so far. The redirection works perfectly. I just need to put the value into the url as a parameter. I don’t know the basics or theories of javascript. I just google and manage to put them together. Could anyone please help me out?
Thanks!

<script>
  function getinputval()
    {
        var numpages1 = document.getElementById("numberofpages1").value;} 
document.addEventListener( 'wpcf7mailsent', function( event ) {
if (document.getElementById('selectservice').value=='Certified Translation') {location.replace('https://example.com?add-to-cart=856&quantity=+numpages1;')}
else if (document.getElementById('selectservice').value=='Business Translation') {location.replace('http://www.redirectedpage2.com')}
else { location.replace('http://www.redirectedpage3.com/') }
}, false );
</script>