Ok, I am creating a fairly large form in React (only showing three of the fields here), and thus want to utilize a custom hook for the handling. I found an article explaining a way to do this, however, when I try to type text in my input fields they don't get filled. My console.log of the e.target values it looks like the field gets reset after each keystroke. What do I miss? Cheers
I tried to simplify my code, and hope it makes sense:
import React, { useState } from "react";
//various other imports not relevant for this issue
const NetworkConfig = () => {
//Custom Hook inserted here for easy overview. Normally imported from external file
function useFormFields(initialState) {
const [fields, setValues] = useState(initialState);
return [
fields,
(e) => {
setValues({
...fields,
[e.target.id]: e.target.value,
});
},
];
}
const [fields, handleFieldChange] = useFormFields({
apnValue: "",
apnUsernameValue: "",
apnUserPwdValue: "",
});
// I omitted the submit button and its functionality in this post,
// to keep my problem clear
// The TextField component basicaly just adds some functionality not
// relevant to this problem. It is tested in other scenarios so in this
// case it basically just works as a normal HTML input[type="text"] field
return (
<div>
<div className="network-config-modal" id="network-config">
<div>
<div>
<h2>Network Config</h2>
</div>
<div className="network-config-row">
<div className="network-config-col">
<h3>Cellular Settings</h3>
<section className="network-config-section">
<TextField
value={fields.apnValue}
onChange={handleFieldChange}
label="APN"
outerLabel={true}
light={true}
type="text"
name="apn"
id="apn"
/>
<TextField
onChange={handleFieldChange}
value={fields.apnUsernameValue}
label="APN Username"
optional={true}
outerLabel={true}
light={true}
name="apn-username"
id="apn-username"
/>
<TextField
onChange={handleFieldChange}
value={fields.apnUserPwdValue}
label="APN Password"
optional={true}
outerLabel={true}
light={true}
name="apn-password"
id="apn-pwd"
/>
</section>
</div>
</div>
</div>
</div>
</div>
);
};
export default NetworkConfig;