Skip to content

Commit

Permalink
[tanstack-query] "Refresh button" idiomatic TanStack Query
Browse files Browse the repository at this point in the history
  • Loading branch information
dgroomes committed Jan 13, 2024
1 parent d6b1215 commit 39a1bce
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
2 changes: 1 addition & 1 deletion tanstack-query/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Follow these instructions to build and serve the program:
General clean-ups, todos and things I wish to implement for this project:

* [x] DONE Implement
* [ ] How to implement "refresh this data"? If I had a refresh button, do you call some method to invalidate the cache
* [x] DONE (very nice, TanStack Query delivering excellently on its promise) How to implement "refresh this data"? If I had a refresh button, do you call some method to invalidate the cache
for that key or something?


Expand Down
14 changes: 11 additions & 3 deletions tanstack-query/src/app.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import React from 'react';
import React, {useCallback} from 'react';
import ReactDOM from 'react-dom/client';
import {QueryClient, QueryClientProvider, useQuery,} from '@tanstack/react-query';

const queryClient = new QueryClient();

function News() {
console.log("[News] Render function invoked.");
// What is 'isFetching' for if we already have 'status'?
const {status, data, error, isFetching} = useQuery({
const {status, data, dataUpdatedAt, error, isFetching} = useQuery({
queryKey: ['front-page-news'],
queryFn: async () => {
console.log("[queryFn] invoked.");
Expand All @@ -19,6 +18,11 @@ function News() {
},
});

const refreshData = useCallback(() => {
// noinspection JSIgnoredPromiseFromCall
queryClient.invalidateQueries('front-page-news');
}, []);

if (status === "pending") {
return <div>Loading...</div>;
}
Expand All @@ -35,6 +39,10 @@ function News() {
<p>{headline.summary}</p>
</div>
))}
<button onClick={refreshData} disabled={isFetching}>
Refresh {isFetching ? "(loading...)" : ""}
</button>
<p style={{color: '#888'}}>Last fetched at {new Date(dataUpdatedAt).toLocaleString()}</p>
</div>
);
}
Expand Down

0 comments on commit 39a1bce

Please sign in to comment.