How to Indicate Data Fetching from Server vs Cache in React Query V5?
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
In React Query V5, is there a way to determine whether the data is coming from the cache or being fetched from the server?
I want to show a loading state even if the data is retrieved from the cache, so users know that a new search has been triggered.
Since cached data loads instantly, users might not realize if it's being updated.
I want to show a loading state even if the data is retrieved from the cache, so users know that a new search has been triggered.
Since cached data loads instantly, users might not realize if it's being updated.
3 Replies
American black bear
well you should probably create a debounce to not spam the server with requests, so instead of calling the server everytime a user types a letter you wait let's say 200ms and if the user has not typed anything you then send request to the server. this way you reduce the server load and also can use time between requests to show user loading
American black bear
here is a simple example:
// time in ms between user stopping to type and request being sent to server
const SLEEP_DURATION = 200
export default function DebounceSearch() {
const [isLoading, setIsLoading] = useState(false)
const [query, setQuery] = useState("")
const [results, setResults] = useState([])
useEffect(() => {
async function fetchResults(query: string) {
// fetch results logic
}
const handler = setTimeout(async () => {
setIsLoading(true)
const { data } = await fetchResults(query)
setResults(data)
setIsLoading(false)
}, SLEEP_DURATION)
return () => clearTimeout(handler)
}, [query])
return (
/*
Here you can use "isLoading &&" to conditionally render a spinner
You can use "results.map" to display results
*/
)
}
Polar bearOP
thank you!