Home > front end >  How do I get the previous value of a field in React? I want to use it to display the user's pre
How do I get the previous value of a field in React? I want to use it to display the user's pre

Time:09-17

I'd like the first Textfield in the code block below to show the previous value input, so that the user clicks edit, sees the previous value and then can edit from there.

Any help is appreciated!!

This first section covers the initial state

const [tasks, setTasks] = useState([
{
  id: 1,
  text: "Doctor's appointment",
  priority: true,
  isComplete: false
},
{
  id: 2,
  text: "Birthday Dinner",
  priority: true,
  isComplete: false
}]);

The edit function is below

const [taskEditing, setTaskEditing] = useState(null);

const [editingText, setEditingText] = useState("");




function editTask(id) {
const updatedTasksEdit = [...tasks].map((task) => {
  if (task.id === id) {
    task.text = editingText;
  }
  return task;
});
setTasks(updatedTasksEdit);
setTaskEditing(null);
setEditingText("");}

The UI for the task card where I'm trying to edit the task is below

<Card
  style={{
    backgroundColor: `${
      task.isComplete ? "lightgreen" : task.priority ? "lightcyan" : ""
    }`
  }}
>
  {taskEditing === task.id ? (
    <CardHeader
      action={
        <IconButton aria-label="SaveEdits">
          <SaveIcon onClick={() => editTask(task.id)} />
        </IconButton>
      }
      title={
        <TextField
          style={{ width: 410 }}
          required
          variant="outlined"
          onChange={(e) => setEditingText(e.target.value)}
          defaultValue='hello'
          placeholder='This is a placeholder'
          value={editingText}
        />
      }
    />
  ) : (
    <CardHeader
      action={
        <IconButton aria-label="Edit">
          <EditIcon onClick={() => setTaskEditing(task.id)} />
        </IconButton>
      }
      title={task.text}
    />
  )}

CodePudding user response:

To have a copy of the old value, you can use a ref.

  const [editingText, setEditingText] = useState("")
  const oldText = useRef("")
  
  const onClick = () => {
    oldText.current = editingText
    // now the oldText.current holds the old value
    setEditingText("Hello World")
  }

  ...

The difference of using a state vs a ref is that the ref doesn't trigger render, so might help you reduce unnecessary rendering. However in your case, maybe you can try using a state as well.

But you get the point, if you need a previous value, you need to create another variable. You could think the hook state is just a variable. Thus use your general programming logic sense then.

  • Related