Persist user-selected table sort across sessions

Here's a fun use case for using our local storage API: remembering the table sorting that a user's selected for future sessions. By default, Retool apps always loads tables with the default column sorting. If you want to let your users sort tables and then persist the same sort when they return to the same app, follow along...

Step 1: Add a JS query to save the sort direction to local storage
The query I'm using is called saveSortToLocalStorage. We will return to this query in step 3. Here is the full query text:

localStorage.setValue("sort",table1.sort)

Step 2: Add another JS query to set the table sort from the saved value in local storage.
The query I'm using is called setSortOnTable. We want to have this run on page load, so make sure you go to the advanced tab of the query settings to enable that setting. Here's the full query:

table1.setSort(localStorage.values.sort['0'].id,localStorage.values.sort['0'].desc)

Step 3: Set an event handler on the table to trigger the query from step 1 on the sort change action.
This will trigger saveSortToLocalStorage each time the user sorts the table.

Now, each time your user changes the sort on the table, it will be saved in local storage. Then on page refresh, it will sort the table to the last used sorting!

Here's a GIF of this in action:

3 Likes