Persistent form state support in TanStack Form?
Hi! š
Iām exploring TanStack Form for handling filters in my app. One thing Iāve run into is that when users navigate away from a page and then come back, the filter form resets instead of remembering the previous state.
Ideally, Iād like the form state to persist across navigations ā similar to how filters stick around when you use query params in route history. That way, users can navigate around, then return to the page and still see their previously selected filters without having to re-enter them.
Is there a built-in way (or recommended pattern) in TanStack Form to achieve this? For example, syncing form state with the router/query string, or persisting it in local/session storage.
If not, would this make sense as a feature request?
Thanks!
5 Replies
other-emeraldā¢4d ago
Would this make sense as a feature request?This is the 6th thread about persistence in a week. I assume that answers it? š Yes, there's no inbuilt way to do this yet. However, since so many users ask for it, we'll revive an old PR for persisters. Could you share what you use to store and restore such data? localStorage? A vue library? Something from the framework?
optimistic-goldOPā¢4d ago
Oh I am sorry!
Right now I would figure out if I should sync query params with the form or if I should use localstorage. In vue you would typically use the VueUse library which has the useStorage function to use localstorage.
other-emeraldā¢4d ago
Sorry? For asking? No worries!
It just means thereās lots of requests for it. We havenāt had many posts asking about it, but it seems like itās a big feature that should be ootb
this is also the first vue post for it. I think so far itās been 1 svelte request and the rest was React, so itās always good to see what should be tested for the persister
anyways, one way to do this is to store
formApi.state
in localStorage in an onchange listener (preferably with debounce), and to pass a defaultState: restoredState
thereās two things to note here: One is that itās hard to type (which is why it should be ootb), but more importantly, thereās something with storing proxy objects that might also affect vueoptimistic-goldOPā¢3d ago
Thanks Luca. If itās to any help, you can see how it works in Formkit (a well maintained Vue library) https://formkit.com/plugins/local-storage
seems like a good solution. But I was also wondering if it made more sense to sync query params (window.history) with state. Which I ultimately prefer. I worry about the types though. It would probably work good in my case since I wouldnāt reach the query limit.
FormKit
Save to LocalStorage ā”ļø FormKit
Save unsubmitted user form input to localStorage to prevent data loss.
constant-blueā¢2d ago
Side note: FormKit is awesome. Lovely maintainers per our convos