Minh Anh
Minh Anh

Reputation: 5

Need little help on React hooks

I try to make a todo list with React and Redux Toolkit. In handleSubmit function to add item on list, my setText somehow not set the value to empty string. Here are my full code on Stackblitz: https://stackblitz.com/edit/react-ts-bqmjz1?file=components%2FTodoForm.tsx

const TodoForm = (): JSX.Element => {
  //Input value
  const [text, setText] = useState('');

  const dispatch = useDispatch();

  //setText not working
  const handleSubmit = (e: any) => {
    e.preventDefault();
    if (text.trim().length === 0) {
      return;
    }
    dispatch(addItem({ title: text }));
    setText('');
  };

  return (
    <form className="container-fluid" onSubmit={handleSubmit}>
      <div className="input-group">
        <input
          className="form-control"
          placeholder="Enter the value..."
          onChange={(e: { target: HTMLInputElement }) =>
            setText(e.target.value)
          }
        />
        {/* Submit button */}
        <button type="submit" className="btn btn-primary">
          Add
        </button>
      </div>
    </form>
  );
};

Upvotes: 0

Views: 36

Answers (2)

leo_sheecool
leo_sheecool

Reputation: 113

If I understood well the input does not become empty when you click on the add button. To do that you just have to add value={text} in your input

<input
    className="form-control"
    placeholder="Enter the value..."
    value={text}
    onChange={(e: { target: HTMLInputElement }) =>
    setText(e.target.value)
    }
/>

Upvotes: 0

bopbopbop
bopbopbop

Reputation: 522

You're very close! You just missed the value prop on the input:

value={text}

const TodoForm = (): JSX.Element => {
  //Input value
  const [text, setText] = useState('');

  const dispatch = useDispatch();

  //setText not working
  const handleSubmit = (e: any) => {
    e.preventDefault();
    if (text.trim().length === 0) {
      return;
    }
    dispatch(addItem({ title: text }));
    setText('');
  };

  return (
    <form className="container-fluid" onSubmit={handleSubmit}>
      <div className="input-group">
        <input
          className="form-control"
          placeholder="Enter the value..."
          value={text}
          onChange={(e: { target: HTMLInputElement }) =>
            setText(e.target.value)
          }
        />
        {/* Submit button */}
        <button type="submit" className="btn btn-primary">
          Add
        </button>
      </div>
    </form>
  );
};

Upvotes: 1

Related Questions