Why is the State Refusing to Update in React? [duplicate]

I am trying to set up a component with a modal in Typescript using Next and React-Modal, however whenever I attempt to close the modal, it simply remains open.

"use client"

import ReactModal from "react-modal"
import style from "./styles/PromoCard.module.css"
import { useState } from "react";

export default function PromoCard({promoCode, promoDesc, promoLink}: {promoCode: String, promoDesc: String, promoLink?: String}) {
    const hasLink: Boolean = (promoLink != null && promoLink != undefined)
    const [modalOpen, setModalOpen] = useState(false);

    function closeModal() {
        setModalOpen(false);
        console.log(modalOpen)
    }

    return (
        <div style={{display: "flex", flexDirection: "column", cursor: "pointer"}} onClick={() => setModalOpen(true)}>
            <span>{promoCode}</span>
            <span>{promoDesc}</span>
            {hasLink && <br />}
            {hasLink && <span>{promoLink}</span>}
            <ReactModal shouldCloseOnOverlayClick={true} ariaHideApp={false} isOpen={modalOpen} onRequestClose={closeModal} className={style.modalOverlay}>
                <div>
                    <span>{promoCode}</span>
                    <span>{promoDesc}</span>
                    {hasLink && <br />}
                    {hasLink && <span>{promoLink}</span>}
                    <button onClick={closeModal}>Close</button>
                </div>
            </ReactModal>
        </div>
    )
}

I have already tried changing the order in which the state update is called, but whenever I try to change it to false, it remains unchanged.

Ajax filter returns all posts associated with custom taxonomy

so I’m trying to make ajax filter for custom taxonomy I made, but no matter on which button of term I click all posts from that taxonomy are returned. I want to return posts only associated with that term. Here’s the code from query in ajax function

  $termIds = [7,3,5,4,6];
  $ajaxposts = new WP_Query([
    'post_type' => 'post',
    'posts_per_page' => -1,
    'tax_query' => [
       [
          'taxonomy' => 'acquisition',
          'field'    => 'term_id',
          'terms'    => $termIds,
          'operator' => 'IN'
       ],
    ]
 ]);

Why is my React Native Expo App stuck bundling

Fairly new with React-Native and JS. I’ve been creating a simple login screen, used to work and bundle in my phone with expo go app but after modifying a bit the App.js file when I type “npm start” it simple stays bundling forever unless I close VS code.

There are no additional dependencies or modifications besides what comes default when you create a folder with the npx create-expo-app@latest <name> command.

This is my App.js code

import { StyleSheet, Text, View, TextInput, Button, Image, KeyboardAvoidingView, Platform } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errors, setErrors] = useState({});
  const [isPosting, setIsPosting] = useState(false)

  const validateForm = () => {
    let errors = {}

    if (!email) errors.email = "Email is required"
    if (!password) errors.password = "Password is required"

    setErrors(errors)

    return Object.keys(errors).length === 0;
  }

  const handleSubmit = async () => {
    if(validateForm()) {
      setIsPosting(true)
      console.log(email, password)
      const response = await fetch("IP", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          email: email,
          password: password
        })
      })
      console.log("Submitted:", email, password)
      const newP = await response.json()
      console.log(newP)
      setEmail("");
      setPassword("");
      setErrors({});
      setIsPosting(false)
    }
  }
  return (
    // makes the keyboard not interferre with the container that hass the username and apssswords
    <KeyboardAvoidingView 
      behavior="padding" 
      keyboardVerticalOffset={Platform.OS === 'ios' ? 100 : -170} 
      style={styles.container}
    >
      <View style={styles.form}>
        <Image source={require("C:UsersJan-PCDocumentsCodesJS CodesPasswordVaultassetsadaptive-icon.png")} style={styles.image} />
        <Text style={styles.label}>E-mail</Text>
        <TextInput 
          style={styles.input} 
          placeholder='Enter your E-mail' 
          value={email} 
          onChangeText={setEmail}
        />
        {
          errors.email ? <Text style={styles.errorText}>{errors.email}</Text> : null
        }
        <Text style={styles.label}>Passsword</Text>
        <TextInput 
          style={styles.input} 
          placeholder='Enter your password' 
          secureTextEntry 
          value={password} 
          onChangeText={setPassword}
        />
        {
          errors.password ? <Text style={styles.errorText}>{errors.password}</Text> : null
        }
        <Button title={isPosting ? "Logging in..." : "Login"} onPress={handleSubmit} />
      </View>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    justifyContent: "center",
    paddingHorizontal: 20,
    backgroundColor: "f5f5f5"
  },

  form: {
    backgroundColor: "white",
    padding: 20,
    borderRadius: 10,
    shadowColor: "black",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },

  label: {
    fontSize: 16,
    marginBottom: 5,
    fontWeight: "bold",
  },

  input: {
    height: 40,
    borderColor: "#ddd",
    borderWidth: 1,
    marginBottom: 15,
    padding: 10,
    borderRadius: 5,
  },

  image: {
    width: 200,
    height: 200,
    alignSelf: "center",
    marginBottom: 50,
  },

  errorText: {
    color: "red",
    marginBottom: 10,
  },

});

How it looks in VS Code, will stay bundling as long as VS Code is open while consuming processing power. Every time it gets stuck at a different %

Tried deleting the “node_modules” and “package-lock.json” files and then running npm install but still nothing.

Still quite new so don’t know exactly all the tools I have available to find the source of the problem

Using event listener for all buttons and inputs to play UI audio

wondering if this is possible.

I have various inputs and buttons that I’d like to add sounds to.

So in my code, I have the below:

// Declaring the audio MP3s
        const UISoundInput = document.querySelectorAll("input","button");
        const UISound_Click= new Audio('audio\click.mp3';
        const UIsound_delete= new Audio('audio\delete.mp3');
        const UISound_error= new Audio('audio\error.mp3');
        const UISound_save = new Audio('audio\save.mp3');


// Add Event listener for each input          
        UISoundInput.forEach((AudioEvent) =>{
            AudioEvent.addEventListener("input",()=>{
                switch (AudioEvent.className){
// Check input class name and if it's UICLICK Play the audio file at the volume specified by the UI click volume range input value.

             case "UIClick":
                    const UIClickVolume = document.getElementById("Sounds_ClickValue");
                    UISound_Click.volume= UIClickVolume.value/100;
                    console.log (uiclick)
                    UISound_Click.play;
                     ;
                    break
                }

            })
        })

AS A WORKAROUND I’ve got it to work as a function but I don’t really want to continually load a new audio src eachtime:

    function play() {
        var UISound_Click = new Audio("audio\click.mp3");
        const UIClickVolume = document.getElementById("Sounds_ClickValue");
        UISound_Click.volume= UIClickVolume.value/100;
        UISound_Click.play();
    }

BELOW IS THE HTML

                                                    <div id="Sounds_Click">
                                                        <span> Click</span>
                                                        <input class="UIClick" type="range" min="0" max="100" step="1" value="50" id="Sounds_ClickVolume" oninput="this.nextElementSibling.value = this.value">
                                                        <input class="UIClick" type="number" min="0" max="100" step="1" value="" placeholder="50" id="Sounds_ClickValue" oninput="this.previousElementSibling.value = this.value;play()">
                                                    </div>

Can anyone help explain why this doesnt work on an event listener? The console logging shows that it does work.

Any help would be hugely apprecaited, go easy on me as I am a bit of a dummy!

Improve JS string function

Today, I tried to write a simple function that would display the characters of my string one by one by iterating over a string containing the letters of the alphabet and showing the steps on the screen.

Just out of personal curiosity and fun: how would you write it? Is there something you would optimize, both in terms of readability and complexity?

I’ll provide both the sandbox of the desired behavior and the code for the function.

Sandbox

const buildString = (finalString) => {
  let i = 0;
  let j = 0;

  const tempStringArray = [];
  const cycleLength = finalString.length;

  const interval = setInterval(() => {
    const temp = finalString[i];
    const char = alphabet[j];

    tempStringArray.push(undefined);

    tempStringArray[i] = char;
    name.value = tempStringArray.join('');

    if (temp === char) {
      j = 0;
      i++;
    } else {
      j++;
    }

    if (i >= cycleLength) clearInterval(interval);
  }, 50);
}

how to delete all redis data based on entity or schema

I want to delete all redis data that belongs to specific schema or entity regardless of key/data of each entry. Here is how my client look like.

//set up
const { Client, Entity, Schema } = require('redis-om');

class userEntity extends Entity {}

userSchema = new Schema(
  userEntity,
  {
    id: { type: 'string' },
    info: { type: 'string' },
  },
  {
    dataStructure: 'JSON',
  },
);

userRepository = this.redisClient.fetchRepository(userSchema);
await userRepository.createIndex();

//save data
let userData = this.userRepository.createEntity();
userData.id = '123';
userData.info = 'some user';
id = await this.userRepository.save(userData);

await this.userRepository.expire(id, 3600);

So how to delete all records at once? The records that belongs to either userSchema or userEntity?

`Members.fetch()` and `members.cache.get` never actually returning user

I was trying to get server member from variable that had their ID by using message.guild.members.fetch() and message.guild.members.cache.get(), but no matter what I tried with them, they always returned unkown user or undefined.

I tried:

let usrID = some_id;
//1st attempt
let member = message.guild.members.cache.get(`${usrID.toString()}`);
//2nd attempt
let member = message.guild.members.cache.get(`${usrID}`);
//3rd attempt
let member = message.guild.members.cache.get(usrID);
//4th attempt
let member = message.guild.members.fetch(`${usrID.toString()}`);
//and all the other stuff I tried with first function

return console.log(member)

And as I said, none of these returned what I wanted. I feel like I’m missing something, as the same line of code works flawlessly if I use it in a command that evaluates code using eval(). Please tell me what I could’ve missed.

Automatically add hidden text into selection

How can I “force” browser include a hidden text into selection?
For example:

const map = {
  " ": "·",
  "t": "→",
  "rn": "↵rn",
  "n": "␤n",
  "r": "␍r"
};
const whiteSpaces = t => t.replace(/(rn|[ trn])/g, a => map[a]);
expectedHead.textContent += " " + expected.textContent.length + " chars";
expected.textContent = whiteSpaces(expected.textContent);
document.addEventListener("selectionchange", e =>
{
  const string = getSelection().toString();
  selectedHead.textContent = "selected " + string.length + " chars";
  selected.textContent = whiteSpaces(string);
  result.textContent = selected.textContent === expected.textContent;
    
});
x-hidden
{
  font-size: 0;
  white-space: pre;
  display: inline-block; 
}

pre
{
  border: 1px solid red;
  margin: 0;
}

th
{
  font-size: 0.8em;
}
.container
{
  border: 1px solid black;
  margin-bottom: 0.5em;
}
body
{
  margin: 0;
  padding: 0;
}
<div>select text below:</div>
<div class="container"><div><x-hidden>hidden1 </x-hidden>visible1</div>
<div><x-hidden>v</x-hidden>1.2.3<x-hidden>
    </x-hidden></div>
<div><x-hidden>    hidden2</x-hidden> visible2<x-hidden> hidden3</x-hidden></div></div>

<table border="1">
<tr>
<th id="expectedHead">expected</th><th id="selectedHead">selected</th><th>as expected?</th>
</tr>
<tr>
<td><pre><mark id="expected">hidden1 visible1
v1.2.3
    
    hidden2 visible2 hidden3</mark></pre></td>
<td><pre><mark id="selected"></mark></pre></td>
<td id="result"></td>
</tr></table>

In this example it’s not possible select text exactly as in expected column, because last hidden3 string can only be selected with an extra newline at the end.

Is there a way detect when a text in a specific node is fully selected and if that node has siblings x-hidden elements, force content of these elements into selection?

Next.js instrumentation behaves differently with conditional extracted to variable

This issue came from an earlier issue I created, which was resolved, but the underlying behaviour is so baffling I’m desparate to know what is going on.

Next.js has an experimental feature called Instrumentation that allows code to be run on boot-up. It seems to run both server-side and client-side, so a special check is necessary if nodejs-dependent imports are to be used. I have working code that uses this functionality:

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const os = await require('os');
    console.log(os.hostname());
  }
}

However, the following code does not work:

export async function register() {
  const isServer = process.env.NEXT_RUNTIME === 'nodejs'
  if (isServer) {
    const os = await require('os');
    console.log(os.hostname());
  }
}

The error is:

- error ./instrumentation.ts:12:21
Module not found: Can't resolve 'os'
  10 |   const isServer = process.env.NEXT_RUNTIME === 'nodejs'
  11 |   if (isServer) {
> 12 |     const os = await require('os');
     |                     ^
  13 |     console.log(os.hostname());
  14 |   }
  15 | }

Obviously I can use the first one and be happy. But can anyone explain why the second fails? Perhaps something involving tree shaking, or caching, or…?

Here’s a Stackblitz repro.

How to build typescript files so I can use them in frontend

I got an index.ts file and it basically exports an object and some functions that does some stuff with that object. Below is a minimal example:

export myObject = {a: 1, b: 2}

export function getKeys() {
  return Object.keys(myObject);
}

export function getValues() {
  return Object.values(myObject);
}

I want to use myObject and the exported functions in a TypeScript React frontend. I built the package with the below configuration into the dist folder.

{
  "compilerOptions": {
    "declaration": true,
    "noEmit": false,
    "sourceMap": true
  },
  "exclude": ["src/**/*.test.ts"],
  "extends": "./tsconfig.json"
}

When I import these functions into the React app myObject is undefined and I get the below error when I try to use the functions:

...WEBPACK_IMPORTED_MODULE_1.getKeys is not a function

My vscode automatically recognizes the functions and imports them.

What am I doing wrong or what is missing?

EAS update not loading assets

I have updated my app using eas update last week and it worked fine, this week, using the same project with the same packages, I try to run eas update again, but this time at the end of exporting files and uploading files, I get a warning like error

i 47 iOS assets, 47 Android assets (maximum: 2000 total per update). Learn more about asset limits.: https://expo.fyi/eas-update-asset-limits
git exited with non-zero code: 128

enter image description here

I need to know what is needed here, please. Please let me know if you need more information on this.

image and alert do not show up on mobile device

the image(of the body background) and alert(window.alert(s_list[1]);) do not show up on mobile device, although they show up on regular browser(pc).I tried chrome and google on my device with no vail.I do not know what the reason behind this. please help, thank in advance.

<!DOCTYPE>
<html lang ="en">
<head>
<style type ="text/css">
.container{
font-size: 40px;

color: blue;

border-radius: 50px

}
.button{
background-color: blue;
color: orange;
min-height: 40px;
min-width: 130px;


}
h3{
color: red;
}
</style>
<script type ="text/javascript">
function myarray () {
var s_list = new Array(3);
s_list[0] = "beginner";
s_list[1] = "intermediate";
s_list[2] = "advanced";
s_list[3] = "professional";
window.alert(s_list[1]);
}

</script>

<title>Choose Level</title>
</head>
<h3> Choose your level then tab Click me!</h3>

<body background ="./images/sea.jpg">

<label class = "container"> 
<input type ="radio" name="radio" checked> Beginner
<span class ="check"></span>
</label>
<br>

<label class ="container"> 
<input type ="radio" name ="radio" checked> Intermediate
<span class ="check"</span>
</label>
<br>
<label class ="container"> 
<input type = "radio" name ="radio" checked> Advanced
<span class ="check"></span>

<br>
<br>
<input type ="button" class ="button" value ="click me!" onclick ="myarray()"></button>

</body>
`</html>

I want to set up a web server on a Raspberry Pi and access it from an external network,

I dream of accessing my self-made website from my smartphone when I’m out, but I’m having trouble making it work. I suspect there might be issues with port forwarding, especially, and I would appreciate your assistance.

When I try to set up port forwarding rules for my Google Nest Wifi, the following steps are displayed:

  1. Select the local IP address of the device.
  2. Enter an external port.
  3. Enter an internal port.
  4. Choose TCP, UDP, or TCP/UDP.
    I believe for step 1, I just need to select the fixed local IP address of my Raspberry Pi, but I don’t understand the meaning of steps 2 and 3. I’m getting confused because various ports are involved, such as:
  • For HTTP, the port should be 80, and the external and internal ports should match.
  • The Raspberry Pi’s SSH uses the default port 22.
  • A server set up with Node.js is listening on port 8000.
    Many articles suggest that after setting up port forwarding rules, I should access the global address, but I’m not sure which port (the XXXX part in XXX.XXX.XXX.XXX:XXXX) to use.

Since I think I lack fundamental knowledge of networks, I would also appreciate it if you could recommend some good reference websites.

I couldn’t access raspberry-pi from an external network.