OmidJr
OmidJr

Reputation: 133

Saving object in React.useState

I have a form in my react project, and I want the value of each field to be stored in the state. instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)

import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}

Upvotes: 2

Views: 9447

Answers (3)

subashMahapatra
subashMahapatra

Reputation: 6837

You should create an initial state value if you want to store the form values as an object using useState, so you can rollback to the initial state after an error. Example,

const initialState = {
  name: "",
  email: ""
};

export const UserData = () => {
  const [formState, setFormState] = useState(initialState);

  const submitHandler = event => {
    event.preventDefault();
    console.log(formState);
  };

  return (
    <form onSubmit={submitHandler}>
      <input
        type="text"
        placeholder="Name"
        value={formState.name}
        onChange={e => {
          setFormState({ ...formState, name: e.target.value });
        }}
      />
      <input
        type="email"
        placeholder="Email"
        value={formState.email}
        onChange={e => {
          setFormState({ ...formState, email: e.target.value });
        }}
      />
      <button>Confirm</button>
    </form>
  );
};

Working demo in codesandbox.

Upvotes: 1

edison16029
edison16029

Reputation: 346

React Hooks allows you to define a JavaScript Object using useState. See https://daveceddia.com/usestate-hook-examples/

function LoginForm() {
   const [form, setState] = useState({
   username: '',
   password: ''
});

Update the form using the function :

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

Call the function onSubmit of the button

<form onSubmit={updateField}>
    <input type="text" placeholder="Name" />
    <input type="email" placeholder="Email" />
    <Button >Confirm</button>
</form>

Upvotes: 4

Akhilesh
Akhilesh

Reputation: 524

You can use useState hook. Check this

const [state, setState] = useState({ name, email });

To set the state similar to setState in class based component:

setState({name: 'react', email: 'react'})    

To access the state value:

import React, { useState } from 'react';

export const UserData = () => {
const [state, setState] = useState({ name, email });
  return(
     <form>
        <input type="text" placeholder="Name" value={state.name} />
        <input type="email" placeholder="Email" value={state.email}  />
        <button>Confirm</button>
     </form>
  )
}

Upvotes: 1

Related Questions