Custom useForm Hook does not update field value

Shivam Sinha

In the following example the name does not update: https://codesandbox.io/s/react-hooks-usestate-forked-od9th?file=/src/index.js:0-788

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";


const useForm = initialValues => {
  const [values, setValues] = useState(initialValues);

  return [
    values,
    e => {
      console.log(e.target.value);
      setValues({
        ...values,
        [e.target.name]: e.target.value
      });
    }
  ]
}

let count = 0;

const Hello = (props) => {
  const [values, handleChange] = useForm({ nameInput: props.name });
  count++
  console.log(`RenderedAmount: ${values.nameInput} : ${count}`)
  return (
  <div>
    Name: <input value={values.nameInput} onChange={handleChange}/><br/>
    Hello {values.nameInput}!
  </div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Hello name="John"/>, rootElement);
HichamELBSI

You forgot to give the name to the input.

As you are doing [e.target.name]: e.target.value.

If the name of the input is undefined, you will have {"": value} in your state

<input value={values.nameInput} onChange={handleChange} name="nameInput" />

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Displaying Advanced Custom Field (ACF) value in a WooCommerce hook

From Dev

Update @timetamp field in logstash with custom timestamp value

From Dev

CRM Online Tax Field WIll Not Update After Changing A Value - Custom Plugin

From Dev

Testing return value of a custom hook

From Dev

Update field value in object

From Dev

unable to update the state through custom react hook

From Dev

Update to TFS custom field - optimization

From Dev

React does not render the last hook update it received

From Dev

React hook state - does not update component

From Dev

Pymongo does not update against a field

From Dev

Form field value not sent on update

From Dev

Update email field value in SQL

From Dev

update field value with multiple rows

From Dev

Form field value not sent on update

From Dev

Update MySQL field with a unique value

From Dev

Clojure: Update value of record field

From Dev

Update the value of a field while typing on another field

From Dev

Update a field with an incrementing value that resets based on field

From Dev

Laravel Update field, with another field value

From Dev

Get Attachment Custom Field value

From Dev

Wordpress orderby Custom Field Value

From Dev

Get Attachment Custom Field value

From Dev

VTiger - Custom field with a DB value

From Dev

advance custom field: missing value

From Dev

Send custom field value to email

From Dev

Pass field value to custom layout.Field

From Dev

Pass field value to custom layout.Field

From Dev

Value does not update in array

From Dev

Checkbox in Custom Adapter does not update