Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
9 replies
antoine

need help with keepPreviousData in trpc client / tanstack query

API call:
  const [userToFind, setUserToFind] = useState("");
  const {
    data: foundUsers, // array of objects
    isFetching: isSearchUsersFetching,
    isFetched: isSearchUsersFetched,
  } = api.user.searchByUsername.useQuery(userToFind, {
    enabled: userToFind.length > 0,
    initialData: [],
    refetchOnMount: false,
    refetchOnWindowFocus: false,
    refetchOnReconnect: false,
    retry: false,
    keepPreviousData: true,
  });


rendering foundUsers:
{(isSearchUsersTyping || isSearchUsersFetching) &&
foundUsers.length === 0 ? (
  <CardContent className="flex justify-center py-2">
    Loading...
  </CardContent>
) : foundUsers.length === 0 ? (
  <CardContent className="flex justify-center py-2">
    Results not found
  </CardContent>
) : (
  foundUsers.map((u, idx) => (
    // jsx
  ))
)}


I update userToFind through an input field (its debounced), and I'm trying to prevent Loading... from flashing when foundUsers is refetched. I tried keepPreviousData: true, but it didn't fix this issue. I'm not really sure what the issue could be. I tried staleTime: Infinity, but that just prevents a refetch. For now, I might keep the previous data in a separate state and render that while foundUsers is being refetched. Can anyone help with this? Let me know if you need more details.
Solution
That is the preferred solution for now, keeping the previous data in a state as you are doing
Was this page helpful?