2

I'm trying to implement a very simple text area with a button to delete the content of the text area.

This is my code:

import React, { useState } from "react";

const Info = () => {
  const [desc, setDesc] = useState("Lorem, ipsum dolor sit amet consectetur adipisicing elit.");

  return (
    <div>
      <h1>Info</h1>
      <textarea
        className="form-control"
        id="exampleFormControlTextarea1"
        rows="5"
        placeholder="Add description..."
        value={desc}
        onChange={e => setDesc(e.target.value)}
      ></textarea>
      <button
        onClick={() => {
          console.log("BEFORE: ", desc);
          setDesc("");
          console.log("AFTER: ", desc);
        }}
      >
        Delete
      </button>
    </div>
  );
};

export default Info;

I'm using useState hook to give the functional component a state and I set it to the initial value: "Lorem, ipsum dolor sit amet consectetur adipisicing elit."

In the onClick attribute of the button I added a console.log() before and after setting the state to its new value.

The first time I click on the button I get:

BEFORE: "Lorem, ipsum dolor sit amet consectetur adipisicing elit."
AFTER: "Lorem, ipsum dolor sit amet consectetur adipisicing elit."

The second time I get:

BEFORE: ""
AFTER: ""

I don't understand why the first time i don't get this:

BEFORE: "Lorem, ipsum dolor sit amet consectetur adipisicing elit."
AFTER: ""
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Marco Gelli
  • 319
  • 2
  • 15
  • 7
    This is due to state updates in react being done asynchronously. So long as your textarea is updating correctly, you don't have anything to be concerned about. – silencedogood Nov 22 '19 at 17:29
  • 2
    Possible duplicate of [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Emile Bergeron Nov 22 '19 at 17:51

0 Answers0