How do I get my input to be displayed all at once instead of one by one

35 Views Asked by At

So I am running a string reverse function. I have an input that console logs out whatever was typed into the input in reverse but now my problem is that when the text is being consoled out, it displays the letters one by one and I do not want that. I want it to return all the letters at once as a word. This is what my code looks like.

function Reduxy() {
    const reverse = (str) => {
        let reversedString = '';
        setTimeout(() => {
            for(var i = str.length-1; i >= 0; i--){
                reversedString+=str[i];
            }
            console.log(`Reversed string ${reversedString}`);
        }, 2000);
    }
  return (
    <div>
        <input type="text" placeholder='type word' onChange={e => reverse(e.target.value)} />
        {/* <button onClick={}>Submit</button> */}
    </div>
  )
}

export default Reduxy

Where could I be going wrong?

1

There are 1 best solutions below

0
David On

It's currently writing the values to the console as you type them because the onChange event is invoked with each change here.

Based on this comment above, it sounds like you're not looking to respond to some future event but rather to implement a 2-second de-bounce window, in which the value is logged to the console only if the user has typed something and has stopped typing for 2 seconds.

In React I'd do this with a combination of useState and useEffect. First you'd keep the value in state and all the input does is update that state. Every state update re-renders the component, and useEffect would make use of that by creating a 2-second timeout to display the value, and canceling that timeout any time the component re-renders.

For example:

import { useState, useEffect } from "react";

function Reduxy() {
  // State to store the value
  const [myValue, setMyValue] = useState("");

  useEffect(() => {
    // Ignore the initial state
    if (myValue !== "") {
      // Set a timeout to display the reversed value
      const timeout = setTimeout(() => {
        reverse(myValue);
      }, 2000);

      // Cancel that timeout when the component unmounts
      return () => clearTimeout(timeout);
    }
  }, [myValue]);

  // No changes were made to this function
  const reverse = (str) => {
    let reversedString = "";
    setTimeout(() => {
      for (var i = str.length - 1; i >= 0; i--) {
        reversedString += str[i];
      }
      console.log(`Reversed string ${reversedString}`);
    }, 2000);
  };

  // The input now only updates state
  return (
    <div>
      <input
        type="text"
        placeholder="type word"
        onChange={(e) => setMyValue(e.target.value)}
      />
    </div>
  );
}

export default Reduxy;