Skip to content

Commit

Permalink
chore(rsc): Refactor: Rename RscFetcher -> RscRoutes (#11409)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobbe authored Sep 1, 2024
1 parent 188efb6 commit c01809e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 29 deletions.
14 changes: 7 additions & 7 deletions packages/router/src/rsc/ClientRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { namedRoutes } from '../namedRoutes.js'
import { RouterContextProvider } from '../router-context.js'
import type { RouterProps } from '../router.js'

import { RscFetcher } from './RscFetcher.js'
import { RscRoutes } from './RscRoutes.js'

export const Router = ({ useAuth, paramTypes, children }: RouterProps) => {
return (
Expand Down Expand Up @@ -48,8 +48,8 @@ const LocationAwareRouter = ({
// 'No route found for the current URL. Make sure you have a route ' +
// 'defined for the root of your React app.',
// )
const rscProps = { location: { pathname, search } }
return <RscFetcher rscProps={rscProps} />
const routesProps = { location: { pathname, search } }
return <RscRoutes routesProps={routesProps} />
}

const requestedRoute = pathRouteMap[activeRoutePath]
Expand All @@ -70,7 +70,7 @@ const LocationAwareRouter = ({
)
}

const rscProps = { location: { pathname, search } }
const routesProps = { location: { pathname, search } }

return (
<RouterContextProvider
Expand All @@ -80,18 +80,18 @@ const LocationAwareRouter = ({
activeRouteName={requestedRoute.name}
>
<AuthenticatedRoute unauthenticated={unauthenticated}>
<RscFetcher rscProps={rscProps} />
<RscRoutes routesProps={routesProps} />
</AuthenticatedRoute>
</RouterContextProvider>
)
}

const rscProps = { location: { pathname, search } }
const routesProps = { location: { pathname, search } }
// TODO (RSC): I think that moving between private and public routes
// re-initializes RscFetcher. I wonder if there's an optimization to be made
// here. Maybe we can lift RscFetcher up so we can keep the same instance
// around and reuse it everywhere
return <RscFetcher rscProps={rscProps} />
return <RscRoutes routesProps={routesProps} />
}

export interface RscFetchProps extends Record<string, unknown> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ function rscFetchRoutes(serializedProps: string) {
const searchParams = new URLSearchParams()
searchParams.set('props', serializedProps)

const rscId = '__rwjs__Routes'

// TODO (RSC): During SSR we should not fetch (Is this function really
// called during SSR?)
const responsePromise = fetch(BASE_PATH + '__rwjs__Routes?' + searchParams, {
const responsePromise = fetch(BASE_PATH + rscId + '?' + searchParams, {
headers: {
'rw-rsc': '1',
},
Expand All @@ -70,21 +72,18 @@ function rscFetchRoutes(serializedProps: string) {
callServer: async function (rsaId: string, args: unknown[]) {
// `args` is often going to be an array with just a single element,
// and that element will be FormData
console.log('RscFetcher :: callServer rsaId', rsaId, 'args', args)

// Including rsaId here to make sure the page rerenders when calling RSAs
// Calling a RSA doesn't change the url (i.e. `serializedProps`), and it
// also doesn't change the rscId, so React would not detect a state change
// that would trigger a rerender. So we include the rsaId here to make
// a new cache key that will trigger a rerender.
// TODO (RSC): What happens if you call the same RSA twice in a row?
// Like `increment()`
console.log('RscRoutes :: callServer rsaId', rsaId, 'args', args)

// Including rsaId here for debugging reasons only, what's important is
// `new Date()`, to make sure the cache key is unique so we trigger a
// rerender. It's needed to handle calling RSAs multiple times with the
// same arguments
const rscCacheKey = `${serializedProps}::${rsaId}::${new Date()}`

const searchParams = new URLSearchParams()
searchParams.set('action_id', rsaId)
searchParams.set('props', serializedProps)
const id = '_'
const rscId = '_'

let body: Awaited<ReturnType<typeof encodeReply>> = ''

Expand All @@ -94,7 +93,7 @@ function rscFetchRoutes(serializedProps: string) {
console.error('Error encoding Server Action arguments', e)
}

const responsePromise = fetch(BASE_PATH + id + '?' + searchParams, {
const responsePromise = fetch(BASE_PATH + rscId + '?' + searchParams, {
method: 'POST',
body,
headers: {
Expand All @@ -118,7 +117,7 @@ function rscFetchRoutes(serializedProps: string) {
// rscCache.set(rscCacheKey, dataPromise)

const dataValue = await dataPromise
console.log('RscFetcher :: callServer dataValue', dataValue)
console.log('RscRoutes :: callServer dataValue', dataValue)
// TODO (RSC): Fix the types for `createFromFetch`
// @ts-expect-error The type is wrong for createFromFetch
const Routes = dataValue.Routes?.[0]
Expand Down Expand Up @@ -147,36 +146,36 @@ function rscFetchRoutes(serializedProps: string) {
}

interface Props {
rscProps: RscProps
routesProps: RscProps
}

export const RscFetcher = ({ rscProps }: Props) => {
const serializedProps = JSON.stringify(rscProps)
export const RscRoutes = ({ routesProps }: Props) => {
const serializedProps = JSON.stringify(routesProps)
const [currentRscCacheKey, setCurrentRscCacheKey] = useState(() => {
console.log('RscFetcher :: useState initial value')
console.log('RscRoutes :: useState initial value')
// Calling rscFetchRoutes here to prime the cache
rscFetchRoutes(serializedProps)
return serializedProps
})

useEffect(() => {
console.log('RscFetcher :: useEffect set updateCurrentRscCacheKey')
console.log('RscRoutes :: useEffect set updateCurrentRscCacheKey')
updateCurrentRscCacheKey = (key: string) => {
console.log('RscFetcher inside updateCurrentRscCacheKey', key)
console.log('RscRoutes inside updateCurrentRscCacheKey', key)

setCurrentRscCacheKey(key)
}
}, [])

useEffect(() => {
console.log('RscFetcher :: useEffect about to call rscFetchRoutes')
console.log('RscRoutes :: useEffect about to call rscFetchRoutes')
// rscFetchRoutes will update rscCache with the fetched component
rscFetchRoutes(serializedProps)
setCurrentRscCacheKey(serializedProps)
}, [serializedProps])

console.log('RscFetcher :: current props\n rscProps: ' + serializedProps)
console.log('RscFetcher :: rendering cache entry for\n' + currentRscCacheKey)
console.log('RscRoutes :: current props\n routesProps: ' + serializedProps)
console.log('RscRoutes :: rendering cache entry for\n' + currentRscCacheKey)

const component = rscCache.get(currentRscCacheKey)

Expand Down

0 comments on commit c01809e

Please sign in to comment.