Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page.

The initial URL looks like this:

localhost:3000/?page=1&genres=tree

But upon refreshing the page, the URL becomes:

localhost:3000/

Oddly enough, when I use console.log to check the values of 'page' and 'genres', I can see that the data is still present in the states.

I suspect that the URL is being reset at the server component level, causing the client component to initialize with a blank URL.

This is a snippet of my code:

'use client'
import React from 'react'
import {
  useQueryState,
  parseAsArrayOf,
  parseAsString,
  parseAsInteger,
} from 'next-usequerystate'
import Filters from './Filters'
import ListItem from './ListItem'

const ListProvider = () => {
  const [genres, setGenres] = useQueryState(
    'genres',
    parseAsArrayOf(parseAsString).withDefault([])
  )
  const [pageIndex, setPageIndex] = useQueryState(
    'page',
    parseAsInteger.withDefault(1)
  )

  return (
    <>
      <Filters genres={genres} setGenres={setGenres} />
      <ListItem
        genresFilters={genres}
        setGenres={setGenres}
        pageIndex={pageIndex}
        setPageIndex={setPageIndex}
      />
    </>
  )
}

export default ListProvider

To tackle this problem, I attempted the following solution:

  useEffect(() => {
    setGenres(genres)
    setPageIndex(pageIndex)
  }, [])

While this workaround seems to work, I do not consider it to be an ideal solution. Are there others facing similar challenges? Any suggestions or assistance would be greatly appreciated.

Answer №1

There seems to be an issue with hydration in the next-usequerystate package you are utilizing. Upon page refresh, next-usequerystate sets the initial state based on the default value. To address this issue, consider using next/router along with useEffect from next.js to hydrate after the refresh.

const router = useRouter();

const [genres, setGenres] = useQueryState(
    'genres',
    parseAsArrayOf(parseAsString).withDefault([])
);

const [pageIndex, setPageIndex] = useQueryState(
    'page',
    parseAsInteger.withDefault(1)
);


useEffect(() => {
    const { query } = router;
    setGenres(query.genres || []);
    setPageIndex(query.page || 1);
}, [router, setGenres, setPageIndex]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Introducing an innovative Serverless Multi-user Blogging Platform utilizing Next.js, Tailwind, and AWS CLI for seamless content creation and management

Seeking assistance as I may have overlooked a step. Any guidance is appreciated! Recently, I managed to deploy a full-stack serverless nextJs application on AWS Amplify successfully. I made modifications by adding a new field while creating a new blog pos ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

What is the best way for my web application to interface with a serial port?

I am working on a cloud-based web application that uses ASP Web API and Angular, both hosted on Azure. I have a requirement for my Angular app to communicate with a serial port for reading and writing data. How can I achieve this functionality? I've ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...

Understanding Arrays in Angular JSIn this article, we

I am new to working with Angular JS. Currently, I am populating an array and attempting to showcase its contents on the HTML page using ng-repeat. $scope.groupedMedia = []; // Elements are being added through a for loop. $scope.groupedMedia[year].push(r ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

Tips for enabling resize functionality on individual components one at a time

Check out my Codepen link for the resizable event While using Jquery UI resizable, everything is functioning correctly. However, I am now looking to have the resizable event activate one block at a time. When another block is clicked, the resizable event ...

Guide on How to Upload Huge Files Using a Single Connection in JavaScript

As I work on writing some HTML/JS code to enable the uploading of large files (multi-GB) to a remote server, I am facing some challenges. In the past, we relied on a flash uploader that sent a file in a single network request. However, using flash has now ...

Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this: const arrayOfArrays: number[][] = [[1, 2], [1, 3]]; The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]]. I found a solution using the following approach: // initialize an e ...

Appending a forward slash at the end of a URL seamlessly directs the user to a serendipitous webpage experience, while

I'm currently developing a project on this website: Interestingly, when you append a forward slash to the end of the URL, all the images mysteriously disappear. Consequently, I am unable to include Google AdWords tracking code at the end of any URLs: ...

Export all entries without taking into account pagination limits

My current setup involves using Datatables with pagination. I recently integrated the Datatable.buttons library to enable an Export to Excel feature. However, I encountered a limitation where only the first 10 rows on the current page are exported due to p ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...

Ways to filter out specific fields when returning query results using Mongoose

I was wondering about the code snippet below: Post.create(req.body) .then(post => res.status(201).json(post)) .catch(err => res.status(500).json(err)) While this code works perfectly, I am curious about excluding a specific field, such as the __v fi ...

Tips for disabling viewport resizer while accessing the Console panel in Chrome using Control+Shift+J

Currently, I am utilizing the viewport resizer in Chrome to preview how my code appears on various devices. However, I have encountered an issue - whenever I try to access the console using ctrl + shift + j, the viewport resizer opens instead. You can obs ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

There seems to be an issue with AJAX form submission and it is not functioning properly

Having trouble submitting a form to another page using ajax, as it is not sending the post request. I have included Javascript at the top of the page: <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function(){ ...

Switch the 360-degree images by clicking a button using Panolen.js

As a beginner in the world of html, css, and javascript, I am trying to create a webpage that displays 360 panorama images. My goal is to have the image change when a button is clicked - for example, clicking on button 1 will display image1, while clicking ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...