Reputation: 173
I using next-usequerystate library with Next Js 13, my problem is that when I refresh the page the state on url is lost . This is the url:
localhost:3000/?page=1&genres=tree
When I refresh the page the URL will be :
localhost:3000/
But if I check with console.log(page) and console.log(genres) my states I see the data
I think that the URL started on server component so when my client component start with the status the URL is already setted.
This is 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
I tried to avoid the problem with this solution :
useEffect(() => {
setGenres(genres)
setPageIndex(pageIndex)
}, [])
I don't think is a good solution, but it works.
is there anyone having the same problem? Can you help me?
Upvotes: 0
Views: 321
Reputation: 46
it appears there is a hydration issue in next-usequerystate
package you are using, because when you refresh the page next-usequerystate
it sets the initial state based on default value. your workaround this issue can be by using the next/router with useEffect of 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]);
Upvotes: 0