-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Feature Request: Return timestamp of last revalidation #1322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I don't think this will be a widely needed feature. But you can attach the timestamp in your fetcher as a work around: const fetcher = async (...args) => {
const data = await fetchData(...args)
return [data, Date.now()]
}
// ...
const { data: [data, lastUpdated] } = useSWR('/api', fetcher, {
compare: (a, b) => deepCompare(a[0], b[0])
}) Note that you need to customize the With the latest beta version, you can also create a middleware for it. Check #1160 for more details. |
For others who had this need like me, you can also create a middleware (as shuding said above). Here's a working snippet that adds a import { useEffect, useRef } from "react";
import { SWRConfig, Middleware, SWRHook } from "swr";
const fetchedAtMiddleware: Middleware = (useSWRNext: SWRHook) => {
return (key, fetcher, config) => {
const fetchedAtRef = useRef<Date | undefined>(undefined);
useEffect(() => {
const onSuccess = config.onSuccess;
const onError = config.onError;
config.onSuccess = (...args) => {
fetchedAtRef.current = new Date();
if (onSuccess) onSuccess(...args);
};
config.onError = (...args) => {
fetchedAtRef.current = new Date();
if (onError) onError(...args);
};
}, [config]);
const swr = useSWRNext(key, fetcher, config);
// After hook runs...
return Object.assign({}, swr, {
fetchedAt: fetchedAtRef.current,
});
};
}; Then you can use the middleware using <SWRConfig
value={{
use: [fetchedAtMiddleware]
// ...
}}
/> And then you can use const { data, error, fetchedAt } = useSWR("/api/hello"); Note that if you are using TypeScript, TypeScript will complain that the property // https://github.com/vercel/swr/issues/1599#issuecomment-1287151974
declare module "swr" {
interface SWRResponse {
fetchedAt: Date | undefined;
}
} Hope this can help someone! |
@Armster15 thanks for sharing this! I know this is from a while ago but is it better to use EDIT: Actually, even this doesn't work because it doesn't account for multiple components calling |
Discussed in #802
I'd like to have a go at tackling this, is there any guidance for people wanting to get started with the codebase? I've had a brief look through but not really figured out where/what would be the best thing to do here 😅
Cheers
Originally posted by alii December 10, 2020
For Example
Is this a good idea? Is this feasible?
The text was updated successfully, but these errors were encountered: