forked from caching-tools/next-shared-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrevalidate-button.tsx
52 lines (40 loc) · 1.29 KB
/
revalidate-button.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'use client';
import { usePathname } from 'next/navigation';
import { useState } from 'react';
type RevalidateButtonAppProps = {
nextApi: 'app';
type: 'path' | 'tag';
};
type RevalidateButtonPagesProps = {
nextApi: 'pages';
type: 'path';
};
export function RevalidateButton({
nextApi,
type,
}: RevalidateButtonAppProps | RevalidateButtonPagesProps): JSX.Element {
const pathname = usePathname();
const [revalidation, setRevalidation] = useState('');
function handleRevalidation(): void {
const searchParams = new URLSearchParams();
if (pathname) {
searchParams.set(type, pathname);
}
void fetch(`/api/revalidate-${nextApi}?${searchParams.toString()}`).then(async (result) => {
if (!result.ok) {
setRevalidation('Fail to revalidate');
return;
}
const json = (await result.json()) as { now: string };
setRevalidation(`Revalidated at ${json.now}`);
});
}
return (
<div>
<button data-pw={`revalidate-button-${type}`} onClick={handleRevalidation} type="button">
Revalidate {type}
</button>
<div data-pw={`is-revalidated-by-${type}`}>{revalidation}</div>
</div>
);
}