Replies: 1 comment
-
I've managed to narrow down the issue to the following:
This is unfortunate given that I'm using SSR to retrieve some data and the form lives inside this page. Does anybody went through this problem already? 1. Client page (no full page reload)// actions/demo
'use server';
import { cookies } from 'next/headers';
export async function setNameCookie(prevState, formData) {
const name = formData.get('name');
// Set the cookie
cookies().set('user-name', name, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 7, // 1 week
});
// Return the new state
return { message: `Hello, ${name}! Your name has been saved in a cookie.` };
}
// page.tsx
'use client';
import { setNameCookie } from './actions/demo';
import { useFormState } from 'react-dom';
export default function DemoPage() {
console.log('DemoPage');
const [state, formAction] = useFormState(setNameCookie, { message: '' });
return (
<div>
<form action={formAction}>
<input type="text" name="name" placeholder="Enter your name" />
<button type="submit">Set Name Cookie</button>
</form>
{state.message && <p>{state.message}</p>}
</div>
);
} 2. Server Page (full page reload)// page.tsx
import DemoComponent from './components/DemoComponent';
export default function DemoPage() {
console.log('DemoPage');
return <DemoComponent />;
}
// components/DemoComponent.tsx
'use client';
import { setNameCookie } from './actions/demo';
import { useFormState } from 'react-dom';
export default function DemoComponent() {
console.log('DemoComponent');
const [state, formAction] = useFormState(setNameCookie, { message: '' });
return (
<div>
<form action={formAction}>
<input type="text" name="name" placeholder="Enter your name" />
<button type="submit">Set Name Cookie</button>
</form>
{state.message && <p>{state.message}</p>}
</div>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
Hey folks, I'm trying to set a
cookie
on my Server Action but it's performing a full refresh on the page right after submission. Is this behavior supposed to be intentional? Is there an alternative to prevent this from happening?Something that caught my attention while researching regarding this issue is that you may not use Streaming to set cookies because it would "break" the HTTP protocol of sending all header information at once (video reference). However, after removing all possible
<Suspense>
from the code, it still happens so it doesn't seem quite related to that but how Next.js works underneath.In the contrived example from below, when the form is submitted, the
console.log
fromfetchDataFromDatabase
runs.Additional information
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions