File tree 3 files changed +28
-6
lines changed
3 files changed +28
-6
lines changed Original file line number Diff line number Diff line change 1
1
'use client'
2
2
3
3
import { useTransition } from 'react'
4
+ import { randomColorTheme } from './actions'
4
5
5
6
export function ThemeButton ( ) {
6
7
const [ pending , startTransition ] = useTransition ( )
7
8
return (
8
9
< button
9
10
disabled = { pending }
10
11
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
+ )
16
20
}
17
21
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' } ` }
18
22
>
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -15,7 +15,7 @@ export default async function RootLayout({
15
15
} : Readonly < {
16
16
children : React . ReactNode
17
17
} > ) {
18
- const { data} = await sanityFetch ( { query : THEME_QUERY } )
18
+ const { data} = await sanityFetch ( { query : THEME_QUERY , tags : [ 'theme' ] } )
19
19
20
20
return (
21
21
< html
You can’t perform that action at this time.
0 commit comments