Next.js Discord

Discord Forum

Page moves to top after every action

Unanswered
berkserbet posted this in #help-forum
Open in Discord
I have a server side single page ecommerce app. I have button at the bottom that says "Load More..." that updates a page counter in the query parameters. It isn't a new page - just supposed to extend the existing to include more products. The extension works but the page moves to the top on my browser. How can I make it stay where it was?

My button:
            <div className="flex justify-center p-20">
              <button className="btn btn-accent btn-outline btn-lg" type="submit" formAction={updatePage}>Load More...</button>
            </div>


  async function updatePage(formData: FormData) {
    'use server';
    console.log("Update Page.")
    console.log("Form Data:", formData)
    const newSearchParams = new URLSearchParams();
    allSearchParams.forEach(p => {
      const opts = formData.getAll(p)
      if (opts.length) {
        console.log("Form Data:", p, opts.join(","));
        newSearchParams.append(p, opts.join(","));
      }
    })
    
    if (initialParams.search) {
      newSearchParams.append("search", initialParams.search)
    }
    newSearchParams.set("pages", ((initialParams.pages || 1) + 1).toString())

    redirect(`?${newSearchParams.toString()}`)
  }


I know it has to do with redirect() but I am not sure what else to do?

Better yet - can I make it infinite scroll?

9 Replies

I saw this: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination#adding-pagination

It seems to flip through pages and not extend.
have a look at this to get some good infinite scroll powered by server actions and rsc https://github.com/gabrielelpidio/next-infinite-scroll-server-actions
i got it working well for me with this, and i hope you can too 🙂
Hope so, pretty new to this - but giving it a go!
and i think this example has it so it can auto fetch when reach bottom or just button press which is what i liked about it (also its funny that server actions can return rsc/ server components)
I think server actions always need to be async, what are you asking tho