ashes999
ashes999

Reputation: 1324

NextJs go to new page without refreshing the page and changing the states

I have a NextJS app and I am trying to add dynamic routes to use them as endpoints on my server.

I have a register.tsx file which is loaded when I go to localhost:3000/register

Inside one of the components I want to update the link to /register/user/ however, when I use:

useEffect(() => {
        router.push('/user', undefined, { shallow: true })
    }, [])

Inside my component in goes to a completely new page and loses all the states. How can I achieve this. I have this in my server.ts file:

app.post("/register/user", async (req, res) => {
    
})

EDIT

I was able to fix the issue by changing the file structure of the application to

pages
--register
----[[..slug]].tsx

However, right now:

app.post("/register/user", async (req, res) => {

})

returns an html object wheres I have set it to return a JSON object

Upvotes: 0

Views: 118

Answers (1)

Ivan V.
Ivan V.

Reputation: 8081

You need to move your state up, above all pages in the component hierarchy, so when the pages change, the state stays the same. In your _app.js file you could have a provider that wraps the page component that way every page will have access to the data. For example like this:

        <AuthProvider
          options={{
            clientMaxAge: 0 //60 * 60
          }}
          session={pageProps.session}
        >
            <Component {...pageProps} />
        </AuthProvider>

Now all pages will have access to the data provided by the AuthProvider

Upvotes: 2

Related Questions