Skip to content

Commit b37270c

Browse files
committed
faster theme swap
1 parent 1de06a4 commit b37270c

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

next-enterprise/src/app/ThemeButton.tsx

+9-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
'use client'
22

33
import {useTransition} from 'react'
4+
import {randomColorTheme} from './actions'
45

56
export function ThemeButton() {
67
const [pending, startTransition] = useTransition()
78
return (
89
<button
910
disabled={pending}
1011
onClick={() =>
11-
startTransition(async () => {
12-
await fetch('https://lcapi-examples-api.sanity.dev/api/random-color-theme', {
13-
method: 'PUT',
14-
})
15-
})
12+
startTransition(() =>
13+
randomColorTheme().then((data) => {
14+
if (data?.background && data?.text) {
15+
document.documentElement.style.setProperty('--theme-background', data.background)
16+
document.documentElement.style.setProperty('--theme-text', data.text)
17+
}
18+
}),
19+
)
1620
}
1721
className={`bg-theme-button text-theme-button focus:ring-theme focus:ring-offset-theme focus:outline-hidden cursor-pointer rounded-md px-4 py-2 text-sm font-semibold transition ease-in-out focus:ring-2 focus:ring-opacity-50 focus:ring-offset-2 focus:duration-0 disabled:cursor-not-allowed disabled:opacity-50 ${pending ? 'animate-pulse cursor-wait duration-150' : 'duration-1000'} `}
1822
>

next-enterprise/src/app/actions.ts

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use server'
2+
3+
import {revalidateTag} from 'next/cache'
4+
5+
export async function randomColorTheme() {
6+
const response = await fetch('https://lcapi-examples-api.sanity.dev/api/random-color-theme', {
7+
method: 'PUT',
8+
})
9+
revalidateTag('theme')
10+
if (!response.ok) {
11+
return null
12+
}
13+
const data = await response.json()
14+
if (typeof data === 'object' && 'background' in data && 'text' in data) {
15+
return data as {background: string; text: string}
16+
}
17+
return null
18+
}

next-enterprise/src/app/layout.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export default async function RootLayout({
1515
}: Readonly<{
1616
children: React.ReactNode
1717
}>) {
18-
const {data} = await sanityFetch({query: THEME_QUERY})
18+
const {data} = await sanityFetch({query: THEME_QUERY, tags: ['theme']})
1919

2020
return (
2121
<html

0 commit comments

Comments
 (0)