Save & use data from local storage as initialdata and only fetch if data is not in ls
So here is my use case:
- When a user logs in for the first time, fetch some data about the user from the api
-- This I control with
enabled: authenticated
- Save the fetched data in local storage
-- This I do in the onSuccess function
- On subsequent logins if the data is already present in local storage, do not fetch
-- This I do with first fetching the data from local storage
-- If it is, I combine it with the condition for enabled so enabled: authenticated && !lsData
-- if it is, I also supply that data as initialData to the query
My question is, is this approach good, and is there another built in way to do this with react query in an "easier" way?
My end goal is to simply use LS and not refetch if the data is already in LS, but if its not, then a fetch should be executed.1 Reply
robust-apricot•3y ago
you'd probably want to check out our persisters: https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient
persistQueryClient | TanStack Query Docs
This is set of utilities for interacting with "persisters" which save your queryClient for later use. Different persisters can be used to store your client and cache to many different storage layers.
Build Persisters