Dave.Q
Dave.Q

Reputation: 399

Clear field with useState

I have a form, that when submitted, needs to have the input field cleared.

I'm using useState and inside my addNewColor method, I'm resetting the newName state to go back to an empty string. The initial state is an empty string, so I figured I would just call setName(newName) as that's my initial state, but it didn't work. I know there is some way to use prevState, but I haven't gotten my head around it yet. I apologize for the confusing summary.

In short, I'm just trying to clear the field. I'm using Material UI and the name sits within the TextValidator component.

const NewPaletteForm = () => {
  const [currentColor, setColor] = useState("teal");
  const [colors, setColors] = useState([]);
  const [newName, setName] = useState("");

  function addNewColor() {
    const newColor = {
      color: currentColor,
      name: newName
    };

    const resetName = {
      name: ""
    };

    setName(newName, resetName);
    setColors([...colors, newColor]);
  }

  function handleChange(event) {
    setName(event.target.value);
  }
};

<ValidatorForm onSubmit={addNewColor}>
  <TextValidator
    value={newName}
    onChange={handleChange}
    validators={["required", "isColorNameUnique", "isColorUnique"]}
    errorMessages={[
      "Enter a color name",
      "Color name must be unique",
      "Color is already used"
    ]}
  />
  <Button
    variant="contained"
    type="submit"
    color="primary"
    style={{ backgroundColor: currentColor }}
  >
    Add Color
  </Button>
</ValidatorForm>;

Upvotes: 0

Views: 2170

Answers (2)

Domino987
Domino987

Reputation: 8774

I think you misunderstand the useState hook.

The returned array from useState looks like: ['currentValue', 'methodToSetValue']

So to reset the name, you can simply call setName(""), which will set the current value to "".

If you need the previous value (not to clear but to update from it for example), you can pass a function into setName:

setName(prevName => prevName+' Surname');

This would append Surname to the current name.

Upvotes: 1

Clarity
Clarity

Reputation: 10873

Just use setName('') to reset the name. Also if for some reason you need to get access to the current state, use the functional form of setState:

setName(name => {
  // Do smth with the name
  return name; // Return updated state
);

Upvotes: 1

Related Questions