Next.js Discord

Discord Forum

Next.js router.refresh and get rid of page reload

Unanswered
Yellow croaker posted this in #help-forum
Open in Discord
Yellow croakerOP
Hello i'm currently making app that shows user written data from forms. When i click the submit button my page gets reloaded very fast. Is there way to get rid of this kind behavior, because what i would like to have is that the data is actually updated when user click submit without refreshing the page.
const router = useRouter();

  const onSubmit = async (values: z.infer<typeof personalSchema>) => {
    try {
      const dataToSend = {
        ...values,
        cvId: resume.id,
      };
      const response = await fetch(`/api/resume/${resume.id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(dataToSend),
      });

      router.refresh(); // This makes the page to reload super fast
      if (!response.ok) {
        return toast({
          title: 'something went wrong',
          description: 'Please try again later',
          variant: 'destructive',
        });
      }
      if (response.ok) {
        return toast({
          title: 'Success',
          description: 'Your post has been updated',
          variant: 'default',
        });
      }
    } catch (error) {
      console.error(error);
      return toast({
        title: 'Error',
        description: 'An error occurred while submitting the form',
        variant: 'destructive',
      });
    }
  };

  const { personalInfo } = resume;

  const form = useForm<z.infer<typeof personalSchema>>({
    resolver: zodResolver(personalSchema),
    defaultValues: {
      name: personalInfo.name || '',
      email: personalInfo.email || '',
      phone: personalInfo.phone || '',
      address: personalInfo.address || '',
    },
  });
  return (
    <div>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 mb-4">
...

17 Replies

Yellow croakerOP
export default function ResumeMaker({ resume }: ResumeMakerProps) {
  const [openedForm, setOpenedForm] = useState<
    null | 'personal' | 'work' | 'education'
  >(null);
  console.log('RESUME', resume);
  const [optimisticName, setOptimisticName] = useOptimistic<string>(
    resume.personalInfo?.name || '',
  );

  const handleOptimisticUpdate = (formData: any) => {
    setOptimisticName(formData.name);
  };
  return (
    <div className="grid grid-cols-[1fr,1fr] gap-4 pt-8">
      <div>
        <h1 className="text-2xl font-bold">Aloita CV tekeminen</h1>
        <p className="mb-6">Täytä tietosi</p>

        <div className="mb-2">
          <Card className="mb-4">
            <CardHeader>
              <CardTitle>Personal Info</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="mb-2">
                <PersonalDetailForm
                  resume={resume}
                  onOptimisticUpdate={handleOptimisticUpdate}
                />
              </div>
            </CardContent>
          </Card>
        </div>
        <div className="mb-2">
          <button
            className="w-full p-2 mb-1 bg-gray-200 rounded"
            onClick={() => setOpenedForm(openedForm !== 'work' ? 'work' : null)}
          >
            {openedForm === 'work' ? 'â–¼' : 'â–¶'} Work Experience
          </button>
          <Collapse isOpened={openedForm === 'work'}>
            <WorkExperienceInfo />
          </Collapse>
        </div>
      </div>
      <div>
        <p>{optimisticName}</p>
        <p>{resume.personalInfo?.name}</p>
        <CvTemplate />
      </div>
    </div>
  );


This is where i use PersonalDetailForm
either use window.refresh or unset values at the same time...
@riský either use window.refresh or unset values at the same time...
Yellow croakerOP
How unsetting the values make the values update without refresh?
ahh i thought you said that you wanted to unset them... my bad
router.refesh is designed to keep state, and i don't think you can just disable that
Yellow croakerOP
Yeah i'm fine having the current state kept. But what i want to get rid is the quick refresh on the page. It basically blinks once very fast to refresh the page
are you in dev mode?
Yellow croakerOP
yes npm run dev
try npm run build && npm run start
Yellow croakerOP
yeah i will try, having small error popping atm 🙂
@riský try `npm run build && npm run start`
Yellow croakerOP
I'm so sorry i have to go to school now! but i return to u ASAP !
@riský try `npm run build && npm run start`
Yellow croakerOP
Hello So i made the build and npm run start, but it still has the refresh happening when clicked submit.
Yellow croakerOP
And here is resumeMaker used:
import React from 'react';

import { db } from '@/lib/db';

import { CV, User } from '@prisma/client';
import { getCurrentUser } from '@/lib/session';
import ResumeMaker from '@/components/ResumeMaker';

async function getResumeForUser(resumeId: CV['id'], userId: User['id']) {
  return await db.cV.findFirst({
    where: { id: resumeId, userId },
    include: {
      personalInfo: true,
    },
  });
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Resume = async (params: any) => {
  const user = await getCurrentUser();
  console.log('user in resume', user);
  if (!user) {
    return new Response('Unauthorized', { status: 401 });
  }

  const account = await db.user.findUnique({
    where: { email: user.email ?? '' },
  });
  console.log('account', account);

  if (!account) {
    return new Response('Unauthorized', { status: 401 });
  }

  const resume = await getResumeForUser(params.params.resumeId, account.id);
  console.log('resumeId resume:', resume);

  return (
    <div>
      <ResumeMaker
        resume={{
          id: resume?.id,
          personalInfo: resume?.personalInfo,
          //workExperiences: resume?.workExperiences,
          //educations: resume?.educations,
        }}
      />
    </div>
  );
};

export default Resume;
Return Response? In a function?
@Clown Return Response? In a function?
Yellow croakerOP
I thought that If i find The resumes on this Component, i need to return response? But from your answer i see, that is not The case?

How i should handle The situtation, If user or resumes are not found?
normaly people redirect the user to the login page
@riský normaly people redirect the user to the login page
Yellow croakerOP
Okey gonna fix that. But yeah The building did not help. It still refresh The page The submit is clicked. I found swr by vercel, could that Be help to My problem?