Confused about the setViewState and state management of the ItemView class

I need some help using the setState and getState methods of ItemView?
They are not very well documented, and the type signature is confusing.
When you call leaf.setViewState it requires that you provide a state of type ViewState

WorkspaceLeaf.setViewState(viewState: ViewState, eState?: any):

which is this:

export interface ViewState {

    /**
     * @public
     */
    type: string;
    /**
     * @public
     */
    state?: any;
    /**
     * @public
     */
    active?: boolean;
    /**
     * @public
     */
    pinned?: boolean;
    /**
     * @public
     */
    group?: WorkspaceLeaf;
}

I don’t know what the type property is supposed to be, a string representing what?
The state is expected to be a nested property. But obsidian can call your view’s setState with a value that doesn’t match that signature.
I suspect that this is because it just gives you whathever is serialized in the workspace.json file, and if your view returns something that doesn’t match that, it will just blindly give you that.
Am I right? What is the correct usage?

I’ve written a short guide on setState and getState that might be of interest: https://liamca.in/Obsidian/API+FAQ/views/persisting+your+view+state. We should definitely improve the API documentation around this though.

1 Like

I read that article a while after asking this question. It was a godsend, so thank you for writing it.

My main problem was that I was not making the connection between the way you activate the views normally, as explained in the docs

async activateView() {
    this.app.workspace.detachLeavesOfType(VIEW_TYPE_EXAMPLE);

    await this.app.workspace.getRightLeaf(false).setViewState({
      type: VIEW_TYPE_EXAMPLE,
      active: true,
    });

    this.app.workspace.revealLeaf(
      this.app.workspace.getLeavesOfType(VIEW_TYPE_EXAMPLE)[0]
    );
} 

and when I wanted to provide state to the views, or when your view is called by obsidian after a restart.
For me the piece of code above, was just to activate the view, and nothing else, and I was trying to just pass some state to my views after creating them, so the type key was not making any sense in that context.

Thankfully, after some mistakes I saw they were the same methods, and when that clicked (just some minutes ago) then everything suddenly made sense.

Your article also provided a nice bonus about how to provide a better user experience, so thank you for that too.

1 Like