Below is a simplified version of my code:
const handleEdit = async (event) => {
event.preventDefault();
if (parentLayer === 0) {
const { content, attachment} = event.target.elements;
let contentValue = content.value;
setEditedContent(contentValue);
let attachmentValue = attachment.files[0];
if (contentValue !== content) await updateContent(contentValue);
if (attachmentValue !== undefined && parentLayer === 0) await updateImg(attachmentValue);
} else {
const { content } = event.target.elements;
let contentValue = content.value;
setEditedContent(contentValue);
if (contentValue !== content) await updateContent(contentValue);
}
};
const EditForm = (props) => {
const { content, parentLayer } = props;
const [editedContent, setEditedContent] = useState(content);
<div className='discussion'>
<form className='edit-discussion' onSubmit={handleEdit}>
{parentLayer === 0
?
// Can update img
<input type='file' id='files' name='attachment'/>
<textarea defaultValue={editedContent} required/>
<button type='submit' value='Submit'>submit</button>
:
<textarea defaultValue={editedContent} required/>
<button type='submit' value='Submit'>submit</button>
</form>
</div>
}
In this case, when parentLayer equals 0, the editedContent defaults to {content} which comes from props.
If parentLayer is greater than 0, editedContent is an empty string. However, upon checking with console, {content} holds the correct value.
My question is, why can't the useState set the default value in the second condition?
Here's a screenshot of my program for better visualization:
This is a Reddit-like site, please excuse the unfinished interface: https://i.sstatic.net/uxKln.jpg
During editing, you can see that only the parent layer has the defaultValue: https://i.sstatic.net/ck89g.jpg
Why does React behave in this way?
Update:
The structure of my React program is as follows:
Mainpage => discussion page => By calculation get parentLayer value => when parentLayer equals 0 render the top discussion block, otherwise render the rest of the discussion blocks. Both the top block and the rest block have an editform component.
Essentially, React will render only one page component but many editform subcomponents.
To give a complete visual design, It resembles Reddit layout (apologies for the unfinished design): https://i.sstatic.net/52nfi.jpg