Skip to content

Commit

Permalink
fix: ssr and action updates
Browse files Browse the repository at this point in the history
  • Loading branch information
tannerlinsley committed Nov 12, 2022
1 parent b83fd3a commit 1580062
Show file tree
Hide file tree
Showing 11 changed files with 224 additions and 207 deletions.
1 change: 1 addition & 0 deletions examples/react/basic-ssr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
},
"dependencies": {
"@tanstack/react-router": "0.0.1-beta.8",
"@tanstack/react-router-devtools": "0.0.1-beta.8",
"axios": "^1.1.3",
"react": "^18.2.0",
"react-dom": "^18.2.0"
Expand Down
6 changes: 6 additions & 0 deletions examples/react/basic-ssr/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,13 @@ export async function createServer(
try {
const url = req.originalUrl

if (url.includes('.')) {
console.warn(`${url} is not valid router path`)
return res.status(404)
}

let template, render

if (!isProd) {
// always read fresh template in dev
template = fs.readFileSync(resolve('index.html'), 'utf-8')
Expand Down
2 changes: 2 additions & 0 deletions examples/react/basic-ssr/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react'
import { Outlet } from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'

import { router } from './router'

Expand Down Expand Up @@ -28,6 +29,7 @@ export function App() {
</div>
<hr />
<Outlet />
<TanStackRouterDevtools router={router} />
</>
)
}
11 changes: 8 additions & 3 deletions examples/react/basic-ssr/src/entry-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ export async function render(url: string) {
history: memoryHistory,
})

router.mount()
const unsub = router.mount()
await router.load()

await router.loadLocation()
const routerState = router.dehydrateState()

return [
const res = [
`<script>window.__TANSTACK_ROUTER_STATE__ = JSON.parse(${jsesc(
JSON.stringify(routerState),
{
Expand All @@ -34,4 +34,9 @@ export async function render(url: string) {
</RouterProvider>,
),
]

unsub()
router.reset()

return res
}
4 changes: 2 additions & 2 deletions examples/react/basic-ssr/src/routeConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ export const routeConfig = createRouteConfig().createChildren((createRoute) => [

async function fetchPosts() {
console.log('Fetching posts...')
await new Promise((r) => setTimeout(r, 500))
await new Promise((r) => setTimeout(r, Math.round(Math.random() * 300)))
return axios
.get<PostType[]>('https://jsonplaceholder.typicode.com/posts')
.then((r) => r.data.slice(0, 10))
}

async function fetchPostById(postId: string) {
console.log(`Fetching post with id ${postId}...`)
await new Promise((r) => setTimeout(r, 500))
await new Promise((r) => setTimeout(r, Math.round(Math.random() * 300)))

return await axios
.get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
Expand Down
63 changes: 29 additions & 34 deletions examples/react/kitchen-sink/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,7 @@ const routeConfig = createRouteConfig().createChildren((createRoute) => [
path: '/',
element: <InvoicesHome />,
action: async (partialInvoice: Partial<Invoice>) => {
const invoice = await postInvoice(partialInvoice)
// // Redirect to the new invoice
router.navigate({
to: '/dashboard/invoices/:invoiceId',
params: {
invoiceId: invoice.id,
},
})
return invoice
return postInvoice(partialInvoice)
},
}),
createRoute({
Expand Down Expand Up @@ -133,9 +125,7 @@ const routeConfig = createRouteConfig().createChildren((createRoute) => [
// Your elements can be asynchronous, which means you can code-split!
path: 'expensive',
element: () =>
loaderDelayFn(() => import('./Expensive')).then((res) => (
<res.Expensive />
)),
loaderDelayFn(() => import('./Expensive').then((d) => <d.Expensive />)),
}),
// Obviously, you can put routes in other files, too
// reallyExpensiveRoute,
Expand Down Expand Up @@ -484,14 +474,19 @@ function Invoices() {
} = router.useMatch('/dashboard/invoices')

// Get the action for a child route
const invoiceIndexRoute = router.useRoute('/dashboard/invoices/')
const invoiceDetailRoute = router.useRoute('/dashboard/invoices/:invoiceId')
const invoiceIndexMatch = router.useMatch('/dashboard/invoices/', {
strict: false,
})

const invoiceDetailMatch = router.useMatch('/dashboard/invoices/:invoiceId', {
strict: false,
})

return (
<div className="flex-1 flex">
<div className="divide-y w-48">
{invoices?.map((invoice) => {
const foundPending = invoiceDetailRoute.action.pending.find(
const foundPending = invoiceDetailMatch?.action.submissions.find(
(d) => d.submission?.id === invoice.id,
)

Expand Down Expand Up @@ -530,7 +525,7 @@ function Invoices() {
</div>
)
})}
{invoiceIndexRoute.action.pending.map((action) => (
{invoiceIndexMatch?.action.submissions.map((action) => (
<div key={action.submittedAt}>
<a href="#" className="block py-2 px-3 text-blue-700">
<pre className="text-sm">
Expand Down Expand Up @@ -558,10 +553,13 @@ function InvoicesHome() {
event.preventDefault()
event.stopPropagation()
const formData = new FormData(event.target as HTMLFormElement)
action.submit({
title: formData.get('title') as string,
body: formData.get('body') as string,
})
action.submit(
{
title: formData.get('title') as string,
body: formData.get('body') as string,
},
{ multi: true },
)
}}
className="space-y-2"
>
Expand Down Expand Up @@ -597,7 +595,6 @@ function InvoiceView() {
search,
Link,
navigate,
params,
} = router.useMatch('/dashboard/invoices/:invoiceId')

const [notes, setNotes] = React.useState(search.notes ?? ``)
Expand Down Expand Up @@ -664,19 +661,17 @@ function InvoiceView() {
Save
</button>
</div>
{action.current?.submission?.id === invoice.id ? (
<div key={action.current?.submittedAt}>
{action.current?.status === 'success' ? (
<div className="inline-block px-2 py-1 rounded bg-green-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
Saved!
</div>
) : action.current?.status === 'error' ? (
<div className="inline-block px-2 py-1 rounded bg-red-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
Failed to save.
</div>
) : null}
</div>
) : null}
<div key={action.current?.submittedAt}>
{action.current?.status === 'success' ? (
<div className="inline-block px-2 py-1 rounded bg-green-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
Saved!
</div>
) : action.current?.status === 'error' ? (
<div className="inline-block px-2 py-1 rounded bg-red-500 text-white animate-bounce [animation-iteration-count:2.5] [animation-duration:.3s]">
Failed to save.
</div>
) : null}
</div>
</form>
)
}
Expand Down
20 changes: 15 additions & 5 deletions packages/react-router-devtools/src/devtools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ function Logo(props: React.HTMLProps<HTMLDivElement>) {
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
fontSize: '0.7rem',
fontWeight: '900',
fontSize: '0.8rem',
fontWeight: 'bolder',
lineHeight: '1',
}}
>
Expand All @@ -110,8 +110,15 @@ function Logo(props: React.HTMLProps<HTMLDivElement>) {
TANSTACK
</div>
<div
className="text-transparent bg-clip-text bg-gradient-to-r from-lime-500 to-emerald-500"
style={{
backgroundImage:
'linear-gradient(to right, var(--tw-gradient-stops))',
'--tw-gradient-from': '#84cc16',
'--tw-gradient-stops':
'var(--tw-gradient-from), var(--tw-gradient-to)',
'--tw-gradient-to': '#10b981',
WebkitBackgroundClip: 'text',
color: 'transparent',
letterSpacing: '0.1rem',
marginRight: '-0.2rem',
}}
Expand Down Expand Up @@ -447,7 +454,6 @@ export const TanStackRouterDevtoolsPanel = React.forwardRef<

return (
<ThemeProvider theme={theme}>
<script src="https://cdn.tailwindcss.com"></script>
<Panel ref={ref} className="TanStackRouterDevtoolsPanel" {...panelProps}>
<style
dangerouslySetInnerHTML={{
Expand Down Expand Up @@ -521,8 +527,12 @@ export const TanStackRouterDevtoolsPanel = React.forwardRef<
}}
>
<div
className="flex justify-start gap-2 p-2 items-center"
style={{
display: 'flex',
justifyContent: 'start',
gap: '1rem',
padding: '1rem',
alignItems: 'center',
background: theme.backgroundAlt,
}}
>
Expand Down
Loading

0 comments on commit 1580062

Please sign in to comment.