T
TanStack•2y ago
foreign-sapphire

How to get cache update in another component when data has been updated somewhere else?

Using tanstack/svelte-query. It returns undefined but the data in the cache is updated after fetching.
const queryClient = useQueryClient();
$: cache = queryClient.getQueryState<Game[]>(['games'])

$: console.log('cache', cache)
const queryClient = useQueryClient();
$: cache = queryClient.getQueryState<Game[]>(['games'])

$: console.log('cache', cache)
The code for fetch in the first component:
const query = createQuery({
queryKey: ['games'],
queryFn: () => fetchGames(),
})
const query = createQuery({
queryKey: ['games'],
queryFn: () => fetchGames(),
})
10 Replies
foreign-sapphire
foreign-sapphireOP•2y ago
I don't know if the "getQueryState" will update the component if the cache is updating from somewhere else or not?
noble-gold
noble-gold•2y ago
it does not because its not reactive. you basically always want to call useQuery again
foreign-sapphire
foreign-sapphireOP•2y ago
Sorry I didn't get that completely. Could you please write a little more about this?
noble-gold
noble-gold•2y ago
if you want to read data in another component, use the same useQuery hook with the games queryKey to read that data
noble-gold
noble-gold•2y ago
React Query as a State Manager
Everything you need to know to make React Query your single source of truth state manager for your async state
foreign-sapphire
foreign-sapphireOP•2y ago
Thanks!
foreign-sapphire
foreign-sapphireOP•2y ago
GitHub
query/examples/svelte/basic/src/lib/Posts.svelte at 62704ce63a2c88c...
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query. - TanStack/query
noble-gold
noble-gold•2y ago
it's a different usecase
foreign-sapphire
foreign-sapphireOP•2y ago
Solved with what you wrote on your website. But then why do we have getQueryState and getQueryData?
getQueryState is a synchronous function that can be used to get an existing query's state. If the query does not exist, undefined will be returned.
getQueryState is a synchronous function that can be used to get an existing query's state. If the query does not exist, undefined will be returned.
getQueryData is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, undefined will be returned.
getQueryData is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, undefined will be returned.
As I was confused with the name for State in the getQueryState I thought it was reactive but turns out it was just the state of the data there 🙂 Thanks @TkDodo 🔮
noble-gold
noble-gold•2y ago
for imperative function calls, like if you want to know the current state in an onClick handler. It's also what you need for optimistic updates

Did you find this page helpful?