Answers for "react usestate object update"

6

update object in react hooks

- Through Input

        const [state, setState] = useState({ fName: "", lName: "" });
        const handleChange = e => {
            const { name, value } = e.target;
            setState(prevState => ({
                ...prevState,
                [name]: value
            }));
        };

        <input
            value={state.fName}
            type="text"
            onChange={handleChange}
            name="fName"
        />
        <input
            value={state.lName}
            type="text"
            onChange={handleChange}
            name="lName"
        />
   ***************************

 - Through onSubmit or button click
    
        setState(prevState => ({
            ...prevState,
            fName: 'your updated value here'
         }));
Posted by: Guest on January-02-2021
1

usestate nested object

const [currentApp, setCurrentApp] = useState({
        userID: null,
        hospitalName: null, 
        hospitalID: null,
        date: null,
        time: null,
        timestamp: null,
        slots: 1,
        appointmentType: null
    })
    
const [appointmentType, setAppointmentType] =  useState({
        Granulocytes: {
            bloodType:null,
            message: null
        }
})

const handleGranChange = (e) => {
        setAppointmentType({...appointmentType, Granulocytes : {
            ...appointmentType.Granulocytes, 
            [e.target.id] : e.target.value}
        })
		setCurrentApp({ ...currentApp, ['appointmentType'] : appointmentType  })
        console.log(currentApp)
}
Posted by: Guest on July-06-2020
0

updating one state of an object of states react useState

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

  const printValues = e => {
    e.preventDefault();
    console.log(form.username, form.password);
  };

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

  return (
    <form onSubmit={printValues}>
      <label>
        Username:
        <input
          value={form.username}
          name="username"
          onChange={updateField}
        />
      </label>
      <br />
      <label>
        Password:
        <input
          value={form.password}
          name="password"
          type="password"
          onChange={updateField}
        />
      </label>
      <br />
      <button>Submit</button>
    </form>
  );
}
Posted by: Guest on July-22-2021

Code answers related to "react usestate object update"

Code answers related to "Javascript"

Browse Popular Code Answers by Language