Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>
  );
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading