Reset to Initial State with React Hooks

avatarhzh
:

I'm currently working on a signup form and the following is a snippet of my code:

const Signup = () => {
    const [username, setUsername] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [passwordConfirmation, setPasswordConfirmation] = useState('')

    const clearState = () => {
        setUsername('')
        setEmail('')
        setPassword('')
        setPasswordConfirmation('')
    }

    const handleSubmit = signupUser => e => {
        e.preventDefault()
        signupUser().then(data => {
            console.log(data)
            clearState() // <-----------
        })
    }

    return <JSX />
}

export default Signup

Each piece of state is used for a controlled input for the form.

Essentially what I want to do is after the user has successfully signed up, I want the state to go back to the initial state with the fields cleared.

It's quite imperative to manually set each piece of state back to empty strings inclearState I was wondering if there is a method or function that comes with React that resets the state back to its initial values?

Tholle
:

There is no built-in way to set the state to its initial value, sadly.

Your code looks good, but if you want to decrease the functions needed you can put your entire form state in a single state variable object and reset to the initial object.

Example

const { useState } = React;

function signupUser() {
  return new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
}

const initialState = {
  username: "",
  email: "",
  password: "",
  passwordConfirmation: ""
};

const Signup = () => {
  const [
    { username, email, password, passwordConfirmation },
    setState
  ] = useState(initialState);

  const clearState = () => {
    setState({ ...initialState });
  };

  const onChange = e => {
    const { name, value } = e.target;
    setState(prevState => ({ ...prevState, [name]: value }));
  };

  const handleSubmit = e => {
    e.preventDefault();
    signupUser().then(clearState);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          Username:
          <input value={username} name="username" onChange={onChange} />
        </label>
      </div>
      <div>
        <label>
          Email:
          <input value={email} name="email" onChange={onChange} />
        </label>
      </div>
      <div>
        <label>
          Password:
          <input
            value={password}
            name="password"
            type="password"
            onChange={onChange}
          />
        </label>
      </div>
      <div>
        <label>
          Confirm Password:
          <input
            value={passwordConfirmation}
            name="passwordConfirmation"
            type="password"
            onChange={onChange}
          />
        </label>
      </div>
      <button>Submit</button>
    </form>
  );
};

ReactDOM.render(<Signup />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to conditionally reset state count with react hooks

From Dev

Google map reset to initial state

From Dev

React hooks state Management

From Dev

React Hooks, state not updating

From Dev

Is there a method to reset a react component using ES6 classes to its initial state?

From Java

Reset state to initial with redux-toolkit

From Dev

How reset database back to initial state in rails?

From Dev

How to reset a menu to initial state in JavaScript

From Dev

React initial state. counting

From Dev

How to reset DOM state to the initial state (when page was firstly received?)

From Dev

How do I reset the state to its initial state?

From Dev

MobX - Reset all store observables back to initial state?

From Dev

Is it possible to reset an ECMAScript 6 generator to its initial state?

From Dev

Is RNN initial state reset for subsequent mini-batches?

From Dev

iOS - Is it possible to reset a label/textView to their initial state defined in Interface Builder?

From Dev

How do I reset corrupted pcDuino to its initial state?

From Dev

React/Redux server side rendering initial state

From Dev

React + Flux: Getting initial state into a store

From Dev

Redux React create initial state from API

From Dev

react native get async initial state in reducer

From Dev

getting initial value of local state in react native

From Java

How to change props to state in React Hooks?

From Java

Using Dynamic Var with `Set` State in React Hooks?

From Dev

React Hooks: Passing state prop is NOT a function?

From Dev

React Hooks : Change state of multiple items

From Dev

React Hooks, setTimeOut to set State to false

From Dev

React Hooks - How to use a make a state dependant on another state?

From Java

React useState hook event handler using initial state

From Dev

Async initial state React-Redux Redux-Thunk

Related Related

  1. 1

    How to conditionally reset state count with react hooks

  2. 2

    Google map reset to initial state

  3. 3

    React hooks state Management

  4. 4

    React Hooks, state not updating

  5. 5

    Is there a method to reset a react component using ES6 classes to its initial state?

  6. 6

    Reset state to initial with redux-toolkit

  7. 7

    How reset database back to initial state in rails?

  8. 8

    How to reset a menu to initial state in JavaScript

  9. 9

    React initial state. counting

  10. 10

    How to reset DOM state to the initial state (when page was firstly received?)

  11. 11

    How do I reset the state to its initial state?

  12. 12

    MobX - Reset all store observables back to initial state?

  13. 13

    Is it possible to reset an ECMAScript 6 generator to its initial state?

  14. 14

    Is RNN initial state reset for subsequent mini-batches?

  15. 15

    iOS - Is it possible to reset a label/textView to their initial state defined in Interface Builder?

  16. 16

    How do I reset corrupted pcDuino to its initial state?

  17. 17

    React/Redux server side rendering initial state

  18. 18

    React + Flux: Getting initial state into a store

  19. 19

    Redux React create initial state from API

  20. 20

    react native get async initial state in reducer

  21. 21

    getting initial value of local state in react native

  22. 22

    How to change props to state in React Hooks?

  23. 23

    Using Dynamic Var with `Set` State in React Hooks?

  24. 24

    React Hooks: Passing state prop is NOT a function?

  25. 25

    React Hooks : Change state of multiple items

  26. 26

    React Hooks, setTimeOut to set State to false

  27. 27

    React Hooks - How to use a make a state dependant on another state?

  28. 28

    React useState hook event handler using initial state

  29. 29

    Async initial state React-Redux Redux-Thunk

HotTag

Archive