React input delay handling during onChange event

Upon closer inspection, I've come across an issue that I had not previously noticed. I am unsure if there is a bug within my code or if the onChange function always behaves in this manner, but I am experiencing input delay and am uncertain on how to resolve it. Here is an example to illustrate my point:

https://i.sstatic.net/JOVYU.gif

It is evident that the console only displays the previous state, which is quite inconvenient because it requires the user to click the "Go" button twice in order for it to register the correct state, even if the username and password have been correctly entered.

The code I am working with is relatively simple:

const [state, setState] = useState<LoginStateType>(initialLoginState)
const {username, password} = state

const handleChange = (event: ChangeEventType) => {
    const {name, value} = event.target
    setState({...state, [name]: value})
    console.log(username)
}

{...}

<input type="text" name="username" value={username} onChange={handleChange}/>
<input type="text" name="password" value={password} onChange={handleChange}/>

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

When it comes to asynchronous state updates as detailed in this resource.


Incorporating hooks allows for the following solution:

const [currentState, updateState] = useState(/* initial value */)

updateState(/* new value */)

useEffect(() => {
  // currentState is ensured to be correct
}, [currentState])

Answer №2

Remember, setState is an asynchronous operation - don't expect to get the new value immediately!

Answer №3

My approach may have been a bit convoluted, but it effectively accomplishes the task at hand. In addition to setting up the necessary state for useContext, I also defined two useRef constants:

const inputUserName = useRef<HTMLInputElement | null>(null)
const inputPassword = useRef<HTMLInputElement | null>(null)

{...}

<input type="text" name="username" ref={inputUserName} value={username} onChange={handleChange}/>
<input type={inputType as string} ref={inputPassword} name="password" value={password} onChange={handleChange}/>

The complete code snippet is outlined below:

  //-------------ADMIN STATE-------------
  const [state, setState] = useState<LoginStateType>(iLoginState)
  const {username, password} = state

  //-------------USE EFFECT-------------
    //UseEffect: this is called when the context is set, I think
  useEffect(() => {
    //dispatch must be called before submit, I think because its an asynchronous call
    dispatch(getAdminsRedux());
        setContext(localStorage.getItem('user'))
        if (context !== null){
          navigate("/admin", {replace: true})
        }

  }, [setContext, context, dispatch, navigate]);

  //-------------HANDLE CHANGE-------------
  const handleChange = (event: ChangeEventType) => {
    const {name, value} = event.target
    setState({...state, [name]: value})
  }

  //-------------HANDLE LOGIN-------------
  const handleLogin = async (event: MouseEvent) => {
    event.preventDefault()

    admins.forEach(async (admin)  => {
      if(admin.username === inputUserName.current!.value){
        const comparedHash = compareHash(inputPassword.current!.value, admin.password)
        if (comparedHash){
          setContext(state.username)
          localStorage.setItem('user', state.username)
        }
      }
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to prevent mouse wheel scrolling on a React "number" input field?

Currently, I am encountering an issue with MUI type="number" textfields. When I focus on the field and then scroll the mousewheel, the input value changes unexpectedly. I have looked into adding a blur function after scrolling to prevent this, but I would ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

typescript error: Unable to access properties of an undefined value

I am facing an issue while trying to import a class in my TypeScript code. I have tried using private classA = new ClassA, but it's not working as expected and the result is undefined. Here is my code: import JWT from "../Utils/JWT" import { ...

Improprove the types generated from GraphQL responses

I am facing a major challenge with the types while using GraphQL. My intention is to send a request and store the result in a React state with a well-defined type. However, I want to avoid declaring it as const [animals, setAnimals] = useState<AnimalsLi ...

The parameters 'event' and 'event' are not compatible with each other

I'm currently working on a page that involves submitting a form: import React from 'react'; import Form from 'react-bootstrap/Form'; import { useSignIn } from '../../hooks/Auth/useSignIn'; import { useHistory } from &apos ...

I am looking to implement custom styles to a navigation bar element upon clicking it

When I attempted to use useState(false), it ended up applying the styles to all the other elements in the navbar. import React, { useState } from 'react'; import { AiOutlineMenu } from 'react-icons/ai'; import { Navbar, NavContainer, Na ...

Retrieve the Document ID from Firebase

I'm currently exploring the functionality of Firebase and enhancing my workflow with "react-firebase-hooks". Is there a way for me to retrieve both the doc id and doc data simultaneously and pass them as props? Currently, I am only able to access the ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Encountering an issue with the UNION operator in Typescript causes an error

Currently, I am utilizing the OR operator within Typescript to designate that a product could be of type ProductI OR CartResponseInterface.Product This is how it is structured: product: ProductI | CartResponseInterface.Product However, when attempting t ...

The protractor tool is unable to recognize an Angular component when it is displayed on the page

I have implemented end-to-end (e2e) testing on my project, but I am facing issues that are causing my tests to fail. Below is a snippet of my app.po.ts file: import { browser, by, element } from 'protractor'; export class AppPage { public b ...

What is the best way to retrieve a comprehensive list of all the synthetic event handlers or listeners that have been registered for a

const Rc = <MyReactComponent onChange={(e) => {console.log(e);} onClick={(e) => { workIt(); }} />; How can I retrieve the list of listeners ['onChange', 'onClick'] for the component Rc? I often come across queries ab ...

Is it possible that I am making a mistake when using the multi-mixin helper, which is causing an unexpected compiler error that I cannot

As I work on creating a multi-mixin helper function that takes in a map of constructors and returns an extended map with new interfaces, I come across some challenges. Let's first look at the basic base classes: class Alpha { alpha: string = &ap ...

What methods are available to restrict the values of properties to specific keys within the current type?

I am looking to declare an interface in typescript that is extensible through an indexer, allowing for the dynamic association of additional functions. However, I also want sub properties within this interface that can refer back to those indexed functio ...

Invoking a controller from another controller in the Express framework using Typescript

Currently, I am trying to call a controller from another controller in my code. While attempting to pass parameters using {params: {task_id: String(task_id), result}}, TypeScript is flagging an error indicating that res does not have all the required attri ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...

Interface displaying auto-detected car types

I have a setup that looks like this: interface ValueAccessor<T> { property: keyof T; getPropertyValue: (value: any) => value; } I am trying to figure out how to define the correct type and replace the any when I want to provide a custom ...

Navigating through the keys of a parameter that can assume one of three distinct interfaces in TypeScript: a guide

Here is a function example: function myFunc(input: A | B | C) { let key: keyof A | keyof B | keyof C; for(key in input) { let temp = input[key]; console.log(temp); } } The definitions for A, B, and C are as follows: interfa ...

Transforming dynamic class based on state value from React to TypeScript

I'm trying to implement this React function in TypeScript, but I'm encountering errors. const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> ...