Home > Net >  Reset input field in React (redux)
Reset input field in React (redux)

Time:10-19

I am making a basic Todo application using redux, this is my first time using these methods of redux. I have a problem when I add the Todo the input field does not reset, I have tried various approaches and non seem to work.

For example: defaultValue, handleText on click to bring it back to an empty string, etc.

There are similar question on stack but non with my approach. Here is my code.

enter image description here

Reducer: enter image description here

CodePudding user response:

In order to reset the value of the input field, you just need to set the state value of todos to an empty string, which you would do by calling:

setTodos('');

As you want to do that following the click, you can call setTodos following to the dispatch in the handleClick function:

const handleClick = () => {
  dispatch({ ... });
  setTodos('');
};

Additionally, you might want to initialize todos to a empty string instead of an array as it is used as a value for a text input:

const [todos, setTodos] = useState('');

CodePudding user response:

You have a bug in the TodoInput.

Instead of const [todos, setTodo] = useState([]) you should have something like const [todo, setTodo] = useState("") then in your HandleClick method you should use setTodo("").

  • Related