From 39a1bce9b14431b6100226611f733d3a1f6b47a3 Mon Sep 17 00:00:00 2001 From: David Groomes Date: Sat, 13 Jan 2024 14:31:31 -0600 Subject: [PATCH] [`tanstack-query`] "Refresh button" idiomatic TanStack Query --- tanstack-query/README.md | 2 +- tanstack-query/src/app.jsx | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/tanstack-query/README.md b/tanstack-query/README.md index 7fce62a..984755d 100644 --- a/tanstack-query/README.md +++ b/tanstack-query/README.md @@ -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? diff --git a/tanstack-query/src/app.jsx b/tanstack-query/src/app.jsx index d83090d..c86b9af 100644 --- a/tanstack-query/src/app.jsx +++ b/tanstack-query/src/app.jsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, {useCallback} from 'react'; import ReactDOM from 'react-dom/client'; import {QueryClient, QueryClientProvider, useQuery,} from '@tanstack/react-query'; @@ -6,8 +6,7 @@ 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."); @@ -19,6 +18,11 @@ function News() { }, }); + const refreshData = useCallback(() => { + // noinspection JSIgnoredPromiseFromCall + queryClient.invalidateQueries('front-page-news'); + }, []); + if (status === "pending") { return
Loading...
; } @@ -35,6 +39,10 @@ function News() {

{headline.summary}

))} + +

Last fetched at {new Date(dataUpdatedAt).toLocaleString()}

); }