Saving and Loading, or "Remembering" App State?



Posted Dec 31, 2024

Hello,

I'm working on a Zendesk Support nav bar app and I would like it to remember the state it was in when the user navigates away so that when they come back it puts them right where they were. I think this can be done with client.on('app.deactivated') and client.on('app.activated'), but I'm not sure how to implement this feature. I know it is possible as all of the third party apps we use behave this way.

 

Right now I am just trying to save the scroll position. Here is the code I wrote most recently, which does not work correctly:

/* Save and Load app state to avoid reloading */


 

function saveState() {

    const state = {

        scrollX: window.scrollX,

        scrollY: window.scrollY

    };


 

    client.set('appState', state).then(() => {

        console.log('Scroll position saved:', state);

    }).catch((error) => {

        console.log('Error saving state:', error);

    });

};


 

function loadState() {

    client.get('appState').then((data) => {

        console.log('Data retrieved:', data); // Log the retrieved data

        const state = data.appState;

        if (state) {

            // Restore scroll position

            window.scrollTo(state.scrollX, state.scrollY);

            console.log('Scroll position restored:', state);

        } else {

            console.log('No state found to restore.'); // Log if no state is found

        }

    }).catch((error) => {

        console.error('Error loading state:', error); // Log any errors

    });

}


 

// Call saveState when use navigates away

window.addEventListener('beforeunload', saveState);


 

// Load app state when the app is activated

client.on('app.activated', loadState);

 

 

Any advice is appreciated!

 

Thank you,

Daniel Bernens


0

2

2 comments

Hi Daniel Bernens ,

You may be able to use browser localStorage to help out with this.  There is a sample app in Github that shows how to do this here.

1


image avatar

Erica Girges

Zendesk Developer Advocacy

Hi Daniel,
 
Do you mind clarifying what you mean by the user navigating away? Are they switching browser tabs? Or clicking outside of the app?
 
There should be some level of app state persistence happening meaning if the user is in the nav bar app then clicks into a ticket they should be able to go back to the nav bar app and have their work still there.

1


Please sign in to leave a comment.

Didn't find what you're looking for?

New post