Commit f79a6877 authored by devjiwonchoi's avatar devjiwonchoi

handle reload from hook

parent 3c19f564
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
type DevToolsScale, type DevToolsScale,
} from './preferences' } from './preferences'
import { ShortcutRecorder } from './shortcut-recorder' import { ShortcutRecorder } from './shortcut-recorder'
import { useRestartServer } from '../../error-overlay-toolbar/use-restart-server'
export function UserPreferences({ export function UserPreferences({
hide, hide,
...@@ -69,6 +70,7 @@ export function UserPreferencesBody({ ...@@ -69,6 +70,7 @@ export function UserPreferencesBody({
scale: DevToolsScale scale: DevToolsScale
setScale: (value: DevToolsScale) => void setScale: (value: DevToolsScale) => void
}) { }) {
const { restartServer, isPending } = useRestartServer()
const [theme, setTheme] = useState(getInitialTheme()) const [theme, setTheme] = useState(getInitialTheme())
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
...@@ -105,21 +107,6 @@ export function UserPreferencesBody({ ...@@ -105,21 +107,6 @@ export function UserPreferencesBody({
setScale(value) setScale(value)
} }
function handleRestartDevServer(invalidatePersistentCache: boolean) {
let endpoint = '/__nextjs_restart_dev'
if (invalidatePersistentCache) {
endpoint = '/__nextjs_restart_dev?invalidatePersistentCache'
}
fetch(endpoint, {
method: 'POST',
}).then(() => {
// TODO: poll server status and reload when the server is back up.
// https://github.com/vercel/next.js/pull/80005
})
}
return ( return (
<> <>
<h2 className="dev-tools-info-section-title">General</h2> <h2 className="dev-tools-info-section-title">General</h2>
...@@ -253,10 +240,10 @@ export function UserPreferencesBody({ ...@@ -253,10 +240,10 @@ export function UserPreferencesBody({
data-restart-dev-server data-restart-dev-server
className="action-button" className="action-button"
onClick={() => onClick={() =>
handleRestartDevServer(/*invalidatePersistentCache*/ false) restartServer({ invalidatePersistentCache: false })
} }
> >
<span>Restart</span> <span>{isPending ? 'Restarting...' : 'Restart'}</span>
</button> </button>
</div> </div>
</div> </div>
...@@ -279,10 +266,10 @@ export function UserPreferencesBody({ ...@@ -279,10 +266,10 @@ export function UserPreferencesBody({
data-reset-bundler-cache data-reset-bundler-cache
className="action-button" className="action-button"
onClick={() => onClick={() =>
handleRestartDevServer(/*invalidatePersistentCache*/ true) restartServer({ invalidatePersistentCache: true })
} }
> >
<span>Reset Cache</span> <span>{isPending ? 'Resetting...' : 'Reset Cache'}</span>
</button> </button>
</div> </div>
</div> </div>
......
import { useEffect, useState } from 'react' import { useEffect } from 'react'
import { RefreshClockWise } from '../../../icons/refresh-clock-wise' import { RefreshClockWise } from '../../../icons/refresh-clock-wise'
import { import {
ACTION_RESTART_SERVER_BUTTON, ACTION_RESTART_SERVER_BUTTON,
...@@ -16,30 +16,17 @@ import { css } from '../../../utils/css' ...@@ -16,30 +16,17 @@ import { css } from '../../../utils/css'
* telemetry on how often this is used. * telemetry on how often this is used.
*/ */
export function RestartServerButton({ showButton }: { showButton: boolean }) { export function RestartServerButton({ showButton }: { showButton: boolean }) {
const [disabled, setDisabled] = useState(false) const { restartServer, isPending } = useRestartServer()
const { restartServerAction, isPending } = useRestartServer()
if (!showButton) { if (!showButton) {
return null return null
} }
async function handleClick() {
const hasServerRestarted = await restartServerAction({
invalidatePersistentCache: true,
})
if (hasServerRestarted) {
// Disable the button after a successful restart to prevent multiple server restart.
setDisabled(true)
window.location.reload()
}
}
return ( return (
<button <button
className="restart-dev-server-button" className="restart-dev-server-button"
onClick={handleClick} onClick={() => restartServer({ invalidatePersistentCache: true })}
disabled={isPending || disabled} disabled={isPending}
title="Clears the bundler cache and restarts the dev server. Helpful if you are seeing stale errors or changes are not appearing." title="Clears the bundler cache and restarts the dev server. Helpful if you are seeing stale errors or changes are not appearing."
> >
<RefreshClockWise width={14} height={14} spinning={isPending} /> <RefreshClockWise width={14} height={14} spinning={isPending} />
......
...@@ -3,20 +3,19 @@ import { useState } from 'react' ...@@ -3,20 +3,19 @@ import { useState } from 'react'
export function useRestartServer() { export function useRestartServer() {
const [isPending, setIsPending] = useState(false) const [isPending, setIsPending] = useState(false)
/** const restartServer = async ({
* @returns A Promise that resolves to a boolean value of server restart status.
*/
const restartServerAction = async ({
invalidatePersistentCache, invalidatePersistentCache,
}: { }: {
invalidatePersistentCache: boolean invalidatePersistentCache: boolean
}): Promise<boolean> => { }): Promise<void> => {
setIsPending(true) setIsPending(true)
const url = invalidatePersistentCache const url = invalidatePersistentCache
? '/__nextjs_restart_dev?invalidatePersistentCache=1' ? '/__nextjs_restart_dev?invalidatePersistentCache=1'
: '/__nextjs_restart_dev' : '/__nextjs_restart_dev'
let serverRestarted = false
try { try {
const curId = await fetch('/__nextjs_server_status') const curId = await fetch('/__nextjs_server_status')
.then((res) => res.json()) .then((res) => res.json())
...@@ -29,6 +28,13 @@ export function useRestartServer() { ...@@ -29,6 +28,13 @@ export function useRestartServer() {
return null return null
}) })
if (!curId) {
console.log(
'[Next.js DevTools] Failed to get the current server execution ID while restarting dev server.'
)
return
}
const restartRes = await fetch(url, { const restartRes = await fetch(url, {
method: 'POST', method: 'POST',
}) })
...@@ -39,12 +45,13 @@ export function useRestartServer() { ...@@ -39,12 +45,13 @@ export function useRestartServer() {
'[Next.js DevTools] Failed to fetch restart server endpoint. Status:', '[Next.js DevTools] Failed to fetch restart server endpoint. Status:',
restartRes.status restartRes.status
) )
return false return
} }
// Poll for server restart confirmation. // Poll for server restart confirmation.
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
await new Promise((resolveTimeout) => setTimeout(resolveTimeout, 200)) // generous 1 second delay for large apps.
await new Promise((resolveTimeout) => setTimeout(resolveTimeout, 1_000))
try { try {
const nextId = await fetch('/__nextjs_server_status') const nextId = await fetch('/__nextjs_server_status')
...@@ -53,7 +60,10 @@ export function useRestartServer() { ...@@ -53,7 +60,10 @@ export function useRestartServer() {
// If the execution ID has changed, the server has restarted successfully. // If the execution ID has changed, the server has restarted successfully.
if (curId !== nextId) { if (curId !== nextId) {
return true serverRestarted = true
// Reload the page to ensure the connection to the new server.
window.location.reload()
return
} }
} catch (e) { } catch (e) {
continue continue
...@@ -63,17 +73,20 @@ export function useRestartServer() { ...@@ -63,17 +73,20 @@ export function useRestartServer() {
console.log( console.log(
'[Next.js DevTools] Failed to restart server. Exhausted all polling attempts.' '[Next.js DevTools] Failed to restart server. Exhausted all polling attempts.'
) )
return false return
} catch (error) { } catch (error) {
console.log('[Next.js DevTools] Failed to restart server.', error) console.log('[Next.js DevTools] Failed to restart server.', error)
return false return
} finally { } finally {
setIsPending(false) // If server restarted, don't reset isPending.
if (!serverRestarted) {
setIsPending(false)
}
} }
} }
return { return {
restartServerAction, restartServer,
isPending, isPending,
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment