Next.js Discord

Discord Forum

Using Nextjs Router

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
I have the following component that adds a note to the database.
"use client";

import { useState } from "react";
import { useRouter } from "next/router";

export default function CreateNote() {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const router = useRouter();
  const create = async () => {

    await fetch('http://127.0.0.1:8090/api/collections/notes/records', {
      method: 'POST',
      headers: {
        'Content-Type': "application/json"
      },
      body: JSON.stringify({ title, content })
    })
    setTitle('');
    setContent('');
    router.reload(); // <----- HERE

  }
  return (
    <form onSubmit={create}>
      <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
      <input type="text" value={content} onChange={(e) => setContent(e.target.value)} />
      <button type="submit">Create Note</button>
    </form>
  )
}


notice how I am trying to refresh the page after the user fills in the form so that we can see the new note they added to the local database on front-end
router.reload(); // <----- HERE


I keep getting the error that:
Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted



but i am in a client component, not sure why 😦
Any help or tips are appreciated!

2 Replies

Pull useRouter from next/navigation instead
FYI: that just performs a soft refresh, so your states won't update until you perform a hard one.
There are better ways for state management that someone else could probably help you with
European sprat
And it's router.refresh()