0

I am using useReducer to control my 2 inputs:

const [noteInput, setNoteInput] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
    {
      title: '',
      content: ''
    }
  );

After onClick on button i want both inputs to be cleared. How can i do that after useReducer?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
MichalBart
  • 3
  • 1
  • 5

4 Answers4

0

You can update your state to empty using setState OR You can dispatch other actions for updating that state to the empty string. https://redux.js.org/basics/reducers#reducers

Deeksha gupta
  • 659
  • 6
  • 15
0

If you are just looking to use useReducer to clear your form you can use dispatch to do so. Let's use this example button component as an example.

//Component
<Button onClick={() => {dispatch({ type: "CLEAR_FORM"})}}>Submit</Button>

After clicking the button "CLEAR_FORM" is dispatched to the reducer.

//Form Initial State & Reducer switch statement
export const initialState={
  username:"",
  password:""
}

export const reducer = (state, action) => {
  switch(action.type){
   case: "CLEAR_FORM":
    return {
          username:"",
          password:"",
    }
   default:
    return state
    }
 } 

When the reducer gets the { type: "LOG_OUT" }, in this case, it resets the username and password fields to an empty string.

https://reactjs.org/docs/hooks-reference.html#usereducer

0

You can pass a third argument to React.useReducer() called init. This is called lazy initialization and is a quick way to revert to the initial state.

https://reactjs.org/docs/hooks-reference.html#lazy-initialization

Shah
  • 2,126
  • 1
  • 16
  • 21
0

If you have a Button, you only need to alter onSubmit={handleSubmit} and have the function below and things will be all good. Just remember not to set defaultValue of any TextField or what you are using, just set the value only

const handleReset = (event) => {
    event.preventDefault();
    Object.keys(formInput).forEach((inputKey) => {
        setFormInput({ [inputKey]: '' });
    });
};