Home > Software design >  Update State in React Hooks on Change method
Update State in React Hooks on Change method

Time:12-11

I am wondering why React is not updating the state after a method onChange is called.

Code: enter image description here

export default function App() {
  const [userInput, setUserInput] = useState("");
  const [displayIcons, setDisplayIcon] = useState({
    default: "d-block",
    clear: "d-none"
  });

  const onChange = (e: any) => {
    const _userInput = e.currentTarget.value;
    setUserInput(_userInput);
    console.log("_userInput", _userInput.length);
    console.log("userInput", userInput.length);
    if (_userInput.length > 0)
      setDisplayIcon({ default: "d-none", clear: "d-block" });
    else setDisplayIcon({ default: "d-block", clear: "d-none" });
  };

  const clearText = (e: any) => {
    setUserInput("");
  };

  return (
    <Row>
      <Col>
        <div className="input-group position-relative">
          <div className="form-control">
            <label id="default" className={`${displayIcons.default}`}>
              %
            </label>
            <label className={`${displayIcons.clear}`} onClick={clearText}>
              X
            </label>
            <Input
              type="text"
              className="custom-input"
              placeholder="Enter Something"
              onChange={onChange}
              value={userInput}
            />
          </div>
        </div>
      </Col>
    </Row>
  );
}

CodePudding user response:

Add setting display icon state:

const clearText = (e: any) => {
    setUserInput("");
    setDisplayIcon({ default: "d-block", clear: "d-none" });
};

CodePudding user response:

You will not be able to console.log the updated state value inside of the same function. Try placing your console.log outside of the function and you will see that it does in fact update.

"setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console. To get some behavior of synchronous need to pass function instead of object to setState." - https://www.geeksforgeeks.org/reactjs-setstate/

  • Related