reactjs – React JS – Using textarea control and trying to preserve previous text when onChange event fire

In my React component, I have textarea as an input control. This control displays the text stored in database column. And user can completely or partially update that content from front end and update the value in database column.

My task is to preserve the previous content as well as save the new content (either completely or partially) from this textarea control.

I am using two useState property and onChange() event to set or persist previous and new text and trying to save them in database table. But somehow not able to save or persist previous text.

How can I achieve this?

Here is my code that I have implemented so far.


import React, { useState } from 'react';

const App = () => {
    const [text, setNewText] = useState('');
    const [prevText, setPrevText] = useState('');
}

return (
    <div>
      <textarea
        value={text}
        onChange={(name, value) => {
           const newText = value;
           setPrevText(text);
           setNewText(newText);
        }}
        placeholder="Type something..."
      ></textarea>
      <div>
        <p>Previous Text:</p>
        <p>{prevText}</p>
      </div>
      <div>
        <p>New Text:</p>
        <p>{text}</p>
      </div>
    </div>
);

export default App;

Read more here: Source link