Some days ago I opened anothe thread because I was very confused about how setState and getState methods of views were supposed to be used/implemented. After some experimentation my opinion is that the calls to the setState method are inconsistent between different stages of obsidian lifecycle:
- Activating a view
- Restoring the workspace
- Manually calling set state
This is what I get when my view is called after restoring obsidian (restoring the workspace)
setState of edit form called with:
{title: 'New form', name: 'eeee', fields: Array(2)}
That is just my internal view state, which is what I expect getting because my view doesn’t care about type, or active status, and that is what getState
of my view returns.
However, when you execute a call to setViewState to activate the view like this (directly from the plugin docs):
await this.app.workspace.getLeaf(false).setViewState({
type: viewType,
active: true,
state,
});
What I get on the view is this:
setState of edit form called with:
{type: 'modal-form-edit-form-view', state: {…}}
Here, as you can see, the type is there, and the expected view state is a nested property of the object you get.
But there is more!
If you get the leaf from getLeaf and then call set state on it like this:
const leave = this.app.workspace.getLeavesOfType(viewType)[0]
leaf.setViewState({ type: EDIT_FORM_VIEW, state: theExpectedState });
What you get in the setViewState method?
setState of edit form called with:
{title: 'New form', name: 'eeee', fields: Array(2)}
Yes, exactly the same as when restoring the workspace, which, IMO is the right thing to do.
Why are this calls to this method not all the same? It requires a lot of defensive programming, not to mention how frustrating is to discover this kind of bugs at runtime, and after wasting time chasing them.[