import React, { useState } from "react";
const Form = () => {
const [value, setValue] = useState("");
const [readOnly, setReadOnly] = useState(false);
const handleChange = (event) => {
setValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission logic here
setReadOnly(true);
};
const handleEdit = () => {
console.log(readOnly);
setReadOnly(false);
console.log(readOnly);
};
return (
<form onSubmit={handleSubmit}>
{readOnly ? (
<span>{value}</span>
) : (
<input
type="text"
value={value}
onChange={handleChange}
/>
)}
<br />
{readOnly ? (
<button onClick={handleEdit}>Edit</button>
) : (
<button type="submit">Submit</button>
)}
</form>
);
};
export default Form;
When I click the edit button the state change is not happening properly, How can I control this submit and edit option with react state.
I want the option to edit the value when click edit, but there is some asynchronous nature of react is not allowing me to edit
3
Answers
When you have "submit" type in the form, when there is action, the submit is also called by default. To fix that you can change your submit button to
When you call setReadOnly(false) in the handleEdit function, React does not immediately update the state. Therefore, when you log readOnly right after calling setReadOnly(false), it may still show the previous state value.
You can use the functional form of setState, which accepts the previous state and returns the new state based on it.
I’ve replaced setReadOnly(false) with setReadOnly((prevReadOnly) => !prevReadOnly).