Next.js Discord

Discord Forum

useQuery unintended revalidation when fetching

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
Hello there, I need to understand how to introduce useQuery for the fetching of job posts data so that it can be handled on a client side component.

The primary concern lies in the repetitive execution of usePosts, suggesting a potential revalidation issue triggered by useQuery. This phenomenon adversely impacts the performance and efficiency of the component.

Currently in the implementation of a search bar with autocomplete functionality with an uncontrolled component placed as an input search field and search button.

 import { useQuery } from '@tanstack/react-query'
import getFilteredPosts from './getFilteredPosts';

const fetchPosts = async (query:string) => {
    const postsData: Promise<any> = getFilteredPosts(1, query, ""); // Fetch data for the first page
    const posts: Post[] = await postsData;
    return posts
}

const usePosts = (input:string) => {
  return useQuery({
    queryKey: [input],
    queryFn: (query) => fetchPosts(query.queryKey[0]),
  })
}

export { usePosts, fetchPosts }

2 Replies

American black bearOP
- Every 30 seconds (aprox) usePosts fetches job posts 2 times with no apparent reason
- PostItem gets re-rendered
- Everytime VS code opens usePosts refetches