"use client" w/ TypeScript and calling a server action in useEffect?
Unanswered
erlandsona posted this in #help-forum
We're trying to incrementally adopt Modern Latest NextJS w/ ReactServer Components and Server Actions by initializing it inside an existing Elm spa using a custom element to fetch the index.html and set innerHTML on that custom element. We just started this spike so we're only a few days in and started with npx create-next-app@latest so presumably we're using the latest deps too.
The goal is to leverage the ability for RSC's to "compose" with traditional Client Components to replace our dependency on htmx.js, we weren't fans of it's targeting mechanism for mutible DOM updates and our hope was that we could use React useEffect to trigger refetching / page reloads from the existing CustomEvents we're emitting from Elm.
Everything was working well until we tried to implement the serverAction passing it as a prop to the child Client Component.
Where Home.tsx is
The goal is to leverage the ability for RSC's to "compose" with traditional Client Components to replace our dependency on htmx.js, we weren't fans of it's targeting mechanism for mutible DOM updates and our hope was that we could use React useEffect to trigger refetching / page reloads from the existing CustomEvents we're emitting from Elm.
Everything was working well until we tried to implement the serverAction passing it as a prop to the child Client Component.
const serverAction = async () => {
'use server'
console.log('Revalidating Path?') // This line never gets hit.
revalidatePath('/notes/drafts')
}
return (
<main className="flex flex-col min-h-0 h-full">
<ul id="drafts-list" className="flex flex-col m-0 p-0 h-full overflow-y-auto divide-y divide-neutral-200">
<Home refetch={serverAction}>
{drafts.map((draft, idx) => (
<li
key={idx}Where Home.tsx is
'use client'
import { useEffect } from "react"
// How do we type the Props?
// export type ServerAction<T = undefined> = ((data?: T) => Promise<void>) & Function
// type Children = typeof React.Children
export default function Home({ refetch, children }) {
debugger; // Never gets hit and I can't find Home in the Chrome Devtools either?
useEffect(() => {
const listener = () => {
debugger;
refetch()
}
document.body.addEventListener("draft_created", listener)
return () => document.body.removeEventListener("draft_created", listener)
}, [refetch])
return children
}1 Reply
So turns out the issue stems from trying to embed the NextJS layout.jtsx where the header pieces are being rendered inline with the DOM where Elm is setting the innerHtml... we're exploring alternative ways of initialization so maybe this will clear itself up?