This is Edit profile feature i am trying to build.first i get the user details and fill up the fields by assigning them to a state
const [name, setName] = useState('')
useEffect(() => {
if (localStorage.getItem('userInfo') === null) {
navigate('/login')
}
else{
userInfo=JSON.parse(localStorage.getItem('userInfo'))
setName(userInfo.name)
}
},)
until now everything is fine i can see the name in input field default value
<Form onSubmit={submitHandler}>
<Form.Group controlId='name'>
<Form.Label>Name</Form.Label>
<Form.Control
type='name'
placeholder='Enter name'
defaultValue={name}
onChange={(e) => setName(e.target.value)}
></Form.Control>
</Form.Group>
</Form>
when i submit the form i am still sending the initial value to the server not the edited value.
CodePudding user response:
Maybe you need to call the useEffect only on the component first render by adding [] at the dependency array of the useEffect
CodePudding user response:
You need to add function to onChange Param. I added the code example.
export default function App() {
const [name, setName] = useState(""); // useState hook
// handle change event
const handleChange = (e) => {
e.preventDefault(); // prevent the default action
setName(e.target.value); // set name to e.target.value (event)
};
// render
return (
<div>
<Form>
<Form.Group>
<Form.Control
defaultValue={name}
type="name"
onChange={handleChange}
></Form.Control>
</Form.Group>
</Form>
</div>
);
}
CodePudding user response:
Replace defaultValue
with value
and use the useEffect in this way React useState