I'm working on a Next.js app and trying to create infinite scroll and search input.
Infinite scroll will load 6 more items when ever the user reach the bottom of the page. Search input will filter the results and will return only items with the string input in their title.
Both of the feature works fine alone, the problem is combining them.
The issue stages are:
- enter search input - e.g.
"a"
- scroll to the bottom of the page
Expected: More results with the "a"
search filter on.
Actual: search
is an empty string, so no filter is on the results.
When debugging the scrollHandler
function, search
prop is an empty string, even when search param present in the URL query.
getServerSideProps
:
export async function getServerSideProps({ query }) {
const search = query.search || '';
const limit = query.limit || process.env.ITEMS
const params = {
limit,
skip: process.env.Items_INIT_SKIP,
orderBy: process.env.Items_INIT_ORDERBY,
search
};
const { data: items } = await getItems(params)
return { props: { items, search, limit } }
}
ItemsPage
component:
const ItemsPage = ({ items, search, limit }) => {
const router = useRouter()
useEffect(() => {
window.addEventListener("scroll", handleScroll)
return () => {
window.removeEventListener("scroll", handleScroll)
}
}, [])
const handleScroll = () => {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
const newLimit = 6 + Number(limit);
const path = search ? `${router.pathname}?search=${search}` : router.pathname
const query = { ...router.query, limit: newLimit, search }
router.push({
pathname: router.pathname,
query
},
path)
}
}
const searchHandler = e => {
const search = e.target.value
router.push({
pathname: router.pathname,
query: {
search
},
})
}
return (
<div className={st(classes.root, {})}>
<Input className={classes.Search} value={search} label='search' type='text' onChange={searchHandler} />
<Items items={items} />
</div>
)
}
export default ItemsPage;
from Accessing query values in Next.js
No comments:
Post a Comment