TanStackT
TanStack9mo ago
5 replies
correct-teal

Multiple query keys loading the same data [ANSWERED]

Suppose I have the following screens:
* All posts (GET /posts)
* User's posts (GET /users/{userId}/posts)
* Post details (GET /posts/{postId})

When accessing the post details, I want the initialData to check if this post was previously loaded by either the all posts query, or the user's posts query. I did this in the initial data by checking both separately using queryClient.getQueryData as such:
const {
        data: post,
        isLoading,
        isError,
        refetch,
    } = useQuery({
        queryKey: ['posts', postId],
        queryFn: () => PostsAPI.getById(postId),
        initialData: () => {
            // Check if the post was fetched by userPosts
            const userPosts = queryClient.getQueryData<Post[]>(
                ['userPosts', userId]
            );
            const post = userPosts?.find((p) => p.id === postId);

            if (post) return post;

            // Check if the post was fetched by all posts
            const allPosts = queryClient.getQueryData<Post[]>(
                ['posts']
            );
            const post = allPosts?.find((p) => p.id === postId);

            if (post) return post;
        },
    });

At a first glance this does not look correct because it's violating DRY. But what is the proper way?

The solution that comes to mind is to pass the post as a prop to the post details and have that as the initial data, and meanwhile make a query to posts/{id}, but I'm not 100% sure of this approach
Was this page helpful?