TanStack

T

TanStack

TanStack is a community of passionate software engineers striving for high-quality, open-source software for web devs

Join

react-query-questions

solid-query-questions

table-questions

virtual-questions

router-questions

react-charts-questions

ranger-questions

vue-query-questions

svelte-query-questions

bling-questions

form-questions

angular-query-questions

start-questions

db-questions

start-showcase

router-showcase

📣-announcements

graceful-blue
graceful-blue9/10/2024

Pass initial data in a server component

Hi. I'd like to achive something like this using nextjs app router and tanstack query: 1. Root layout renders and fetches initial user vip level by session id from cookies 2. Root layout renders a QueryClientProvider and passes just fetched level - lets say bronze to the provider 3. Client component somewhere else uses hook useVipLevel which should never be loading because there should be initial data passed on the first user enter even before client components render...
pleasant-yellow
pleasant-yellow9/10/2024

Completely disable cache between two pages.

I just found this thread: https://discord.com/channels/719702312431386674/1003327027849474198/1064541918186442763 So looks like since v4, the behaviour is do not refetch even we set gcTime (cacheTime before v5) to 0. But I want to disable a cache completely, When components mount and unmount, the query should refetch. I also set staleTime to 0 but it's sitll no working. Any suggestions?...
No description
fascinating-indigo
fascinating-indigo9/9/2024

Setting item date string as Date on query

Hey there I was wondering if there's a way to automatically set the incoming date string as a date when the value is returned. I'm using graphql and so it's locked in that the request that I send will contractually send a date back. The thing is, I don't want to have to parse it, or make a new type. I simply want to be able to use it as a date as soon as I get it back. Is there a current way for me to do this or do I need to have 2 types (in typescript) to handle this response? btw: We do not use GraphQL Code Generator in our app ...
rare-sapphire
rare-sapphire9/9/2024

usePrefetchQuery + useQuery for Form Validation

I have a Form where the user inputs an address. Once the Address is entered (Street, Postal Code, City) I fire use usePrefetchQuery to check against a backend if the entered data is a know address When the user submits the form I need to display a option to the user if there where multiple matching locations for the entered data. ...
variable-lime
variable-lime9/9/2024

how to update cache after mutation

I have a component that list a list of users and showing follow status such as "follow, following, follow back", how to update the cache after mutating ``` export function SearchWrapper() { const [searchTerm, setSearchTerm] = useState('') const debouncedSearchTerm = useDebounce(searchTerm, 300);...
adverse-sapphire
adverse-sapphire9/8/2024

useQuery result fails to update when prefetchQuery is used inside loader

Context: I'm using React router 6 with data loaders, and the route I'm testing has 2k DOM nodes I have a prefetchQuery on a loader and a useQuery on the same route, both using the same query, and it works great on first load, but when a prop changes and executes both prefetchQuery and useQuery it runs the queryFn correctly and gets the result on network tab and on TQ devtools but it doesn't update the useQuery result, this only happens sometimes when the page rendering from the data is complex/big enough. It looks like there are some cases where the useQuery result update can be missed if there is a prefetchQuery firing at the same time as the useQuery and the render tree changes is slowing things down, or something like that?...
conscious-sapphire
conscious-sapphire9/7/2024

How to compare previous vs updated data?

Using Query inside a custom hook in a React Native/Expo app. A bit new to React Query so wanted to know best practices to manage this. ```tsx import { useQuery } from "@tanstack/react-query"; ...
future-harlequin
future-harlequin9/6/2024

How to track multiple mutation invocation loading state ?

```tsx const mutation = useMutation(....) <Row onClick={() => mutation.mutate(1)} isLoading={mutation.isLoading} />...
rival-black
rival-black9/6/2024

Multiple queries in v5 - smth like Promise.all([])

Hi guys, i have unfinished snippet of code here which obvs does not work: ```import { ApiClient } from "@services/api/apiClient"; import { useQueries, useQuery } from "@tanstack/react-query"; import { queryKey } from "@utils/queryKeys";...
fascinating-indigo
fascinating-indigo9/6/2024

Structuring query key and userId

Hello guys i have simple question, lets say u want to query user posts, should u then include userId into query key like this?
queryFn: fetchUserPosts, queryKey: ['posts', userId]
queryFn: fetchUserPosts, queryKey: ['posts', userId]
or would just posts as key be sufficient. Currently i'm not passing the user id as argument instead fetching current user inside fetchUserPosts, but i'm curious if this matters. Lets say for example u want to log out or log in as other user. Right now I would need to invalidate queries so that new user gets his...
correct-apricot
correct-apricot9/5/2024

refetch subqueries after refetchInterval on parent has completed

Quick question regarding refetchInterval I have this this query set to refetch every 10 seconds if a condition isnt met ```js...
modern-teal
modern-teal9/4/2024

Refetch all data vs filtered data

I have a click action that filters my list of ingredients like this: ```js queryClient.setQueryData( ['CCCIngredients', selectedCostCenter?.value], (oldData: Ingredient[] | undefined) => {...
graceful-beige
graceful-beige9/3/2024

Is it possible to use setQueryData to update the persisted cache?

pretty much the title. I noticed that setting a query's cache doesn't call the persister. Is it at all possible?
genetic-orange
genetic-orange9/3/2024

Suggestions on Using TanStack Query with SvelteKit

i am building an web app with svelteKit, and currently doing the fetching, pagination, filtering and mutation stuff with build-in load functions and from-actions of sveltekit. the typical url looks like this: https://www.example.com?page=1&scope=enabled&platform=something so everytime page or scope or platform states change, i modify the url params and like goto('{modified-url}') that will trigger the load function again and i get the filtered result. so every state changes, i ned to hit the server. if i use tanstack query, i need to give-up on sveltekit features like form-actions and roll-back to api routes, right?...
stormy-gold
stormy-gold9/3/2024

unable to setup RQ in next.js project

this is my code, ```tsx import { Navbar } from "@/components/Navbar";...
No description
other-emerald
other-emerald9/3/2024

ensureQueryData in route loader and invalidating it

I have a route (_authenticated.tsx) that decides if it should return a Login page or a Layout page with the rest of the application (including the Outlet for the rest of the app). All routes that require authentication are under a folder with the same name (_authenticated). This route has a loader that uses queryClient.ensureQueryData(...) to fetch a /me endpoint from the server. I get access to the returned data by const {data} = useSuspenseQuery(...) with the same queryKey. If the response doesn't have an authenticated user, the route shows Login. If the response has the user, the route renders the application with Outlet. This all works fine. But. Then in the Login page functionality I post the login request to the server. And if the post is successful, my plan was to just use queryClient.invalidateQueries() in the mutate's onSuccess to make the _authenticated.tsx route to get the fresh data of the /me endpoint (with the logged in user) and it would show the Layout component rendering my app....
like-gold
like-gold9/3/2024

Handling Errors in NextJS & React 18 >

Guys, as we know in react 18> the errors thrown with 'throw new Error()' are omitted in production because of security measurements (check this link - https://joulev.dev/blogs/throwing-expected-errors-in-react-server-actions). I might be wrong but I was just wondering how would we go about executing onError callback with a particular error object that comes from a 3rd party API. E.x looking at the server action in the photo and based on the solution from the link above, I am able to use throw new ActionError which makes react to not omit it in production, but the thing is that onError callback won't get triggered in this case because we are just returning the object in the client side....
No description
variable-lime
variable-lime9/2/2024

Minimizing re-renders caused by queries in the parent component of the application

Current tech stack is Static Nextjs application with a Go API and postgres db. In the parent component of the codebase I am trying to fix, there is a custom hook which makes an api call which provides information for the entire application I am working on. The hook takes in 9 arguments which have state information. Some of this information also comes from parameters in the URL. I am trying to mitigate rerenders, as any state change almost anywhere in the app causes cascading rerenders due to the hook. I'm hoping React Query could help, but I'm unsure what my best options are for restructuring this application. I imagine server actions would help, but I'd need a surer direction to go in if I want to restructure the whole application. ...
correct-apricot
correct-apricot9/2/2024

Max refetch count

I am curious what is the proper way to refetch every x amount until maxRefetches has been reached. ```js const { data: job } = useQuery({ ...getJobQueryOpts({...
plain-purple
plain-purple8/30/2024

UX best practices with useQuery invalidateQueries and delayed updates

We have a microservice architecture and one of the downsides is that if we grab information from two different sources and mutate one of these data types and onSuccess of the mutation invalidate both data sources. The invalidate requeries the data source before the change in one microservice has been communicated to and processed by the other microservice. Are there better practices than optimistic updates available for these situations.