onderonur / react-infinite-scroll-hook Goto Github PK
View Code? Open in Web Editor NEWReact hook for creating infinite scroll components.
Home Page: https://onderonur.github.io/react-infinite-scroll-hook/
License: MIT License
React hook for creating infinite scroll components.
Home Page: https://onderonur.github.io/react-infinite-scroll-hook/
License: MIT License
Love this great library.
I was thinking timers weren't the most performant way of checking the boundaries. Should we instead rely on the IntersectionObserver API?
... should be using useRef(null) rather than useRef() .
Please see DefinitelyTyped/DefinitelyTyped#35572
I am trying to use this package in nextjs app directory. But it fails because of calling client components from server files. Since the useLoadItems use useState
it must be declared as client components. So it throws error when calling from page
file.
Attempted to call useLoadItems() from the server but useLoadItems is on the client.
It's not possible to invoke a client function from the server, it can only be rendered as a Component or
passed to props of a Client Component.
Thanks.
I use to be able to use this awesome hook in my nextjs projects but now i am getting weird errors...
Unhandled Runtime Error
TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
Call Stack
eval
node_modules/react-intersection-observer-hook/dist/react-intersection-observer-hook.esm.js (48:0)
eval
node_modules/react-intersection-observer-hook/dist/react-intersection-observer-hook.esm.js (54:0)
eval
node_modules/react-intersection-observer-hook/dist/react-intersection-observer-hook.esm.js (58:0)
M
node_modules/preact/dist/preact.module.js (1:7563)
w
node_modules/preact/dist/preact.module.js (1:2570)
j
node_modules/preact/dist/preact.module.js (1:5833)
w
node_modules/preact/dist/preact.module.js (1:2129)
j
node_modules/preact/dist/preact.module.js (1:5833)
eval
node_modules/preact/dist/preact.module.js (1:1476)
Array.some
<anonymous>
g
node_modules/preact/dist/preact.module.js (1:1382)
eval
node_modules/@prefresh/core/src/runtime/debounceRendering.js (13:0)
Waht does that even mean and how would i start to debug this ?
thanks!
The repo's demo works only if the container is a List ul
or ol
. It should be specified in the README
I have upgraded my project from react 17 to react 18.
also upgraded the react-infinite-scroll-hook 4.01 to 4.04. but it is not working.
Hello everyone, could not find a template for this one.
I was wondering if the threshold could be a ratio of the container instead of a pixel distance, this representation is common in other infinite-list components and what not and seems to me that relates better with the mindset of "when should we load more" since we live on the world of responsiveness.
I know this might be a breaking change, so we there's should be some caution. Either way, here's an example of what I mean?
const infiniteRef = useInfiniteScroll<HTMLDivElement>({
...
threshold: 0.5 // trigger loadMore in the middle of the scroll parent
})
Cheers for the awesomew hook, hope I can help with this one!
In order to keep results list pure, I use the sentryRef as a prop in TS. However, I can't define the type for this prop unless I install react-intersection-observer-hook
and import IntersectionObserverHookRefCallback
from there. Please consider exporting this in your library.
I'm trying to use your library, but doesn't work
Could you help me, please?
Any tips would be greatly appreciated.
Hi,
First of all thank you so much for the amazing package,
I'm trying to implement it with react-query
for a chat application.
Basically, we need to first load most recent messages and when user scrolls to the top of the container, we load old messages.
Just like whatsapp.
I got the load on scroll working and everything is fine.
Just having one small issue:
What happens is on the Initial data load by react-query
the container's scroll position is at the top.
And our sentryRef
element is also on the top, that triggers loadMore
and after loading more still the scroll position stays at top and it just keeps loading more and more, until all the data is loaded.
could you please provide a solution to this problem ๐ข.
Thank you.
Here's the code:
const ChatBox = ({ thread }: ChatBoxProps) => {
const { axios } = useAxios();
const fetchMessages = async ({ pageParam = 0 }) => {
const response = await axios.get(
`/api/v1/message-threads/${thread.id}/messages`,
{
params: {
page_size: 10,
pagination_mode: "cursor",
cursor: pageParam,
sort_field: "created_at",
sort_direction: "desc",
},
}
);
return response.data;
};
const {
isSuccess,
data,
isFetching,
isFetchingNextPage,
fetchNextPage,
hasNextPage,
isError,
} = useInfiniteQuery<MessagesResponse>({
queryKey: ["messages"],
queryFn: fetchMessages,
select: (data) => {
return {
pages: [...data.pages].reverse(),
pageParams: [...data.pageParams].reverse(),
};
},
getNextPageParam: (lastPage, pages) => lastPage.next_cursor,
});
const [sentryRef, { rootRef }] = useInfiniteScroll({
loading: isFetching,
hasNextPage: !!hasNextPage,
onLoadMore: () => fetchNextPage(),
disabled: isError,
rootMargin: "0px 0px 0px 0px",
});
return (
<div className="flex flex-grow flex-col divide-y border-b bg-white">
<ChatHeader thread={thread} />
{/* Chat Messages */}
<div
ref={rootRef}
className="bg-accent h-0 flex-auto flex-col space-y-3 overflow-auto px-4"
>
{isSuccess && (isFetchingNextPage || hasNextPage) && (
<div ref={sentryRef} className="py-3 text-center text-slate-500">
Loading old chats...
</div>
)}
{data?.pages.map((group, i) => (
<Fragment key={i}>
{[...group.data].reverse().map((message) => (
<MessageBubble
key={message.id}
message={message}
direction={
thread.contact_phone_number == message.from
? "inbound"
: "outbound"
}
/>
))}
</Fragment>
))}
</div>
<MessageSender />
</div>
);
};
I am trying to de-mistify
const { data, hasNextPage: newHasNextPage } = await loadItems( items.length, );
The newHasNextPage
got me confused. where does it come from? Is it a typo?
Hello, could you help me out why i cant use this library ? i just import it to my file but it seems doesn't work well.
The error says :
Line 16:5: 'hasNextPage' is not defined no-undef
Line 17:17: 'loadMore' is not defined no-undef
Line 18:17: 'error' is not defined no-undef
Line 67:32: 'hasNextPage' is not defined no-undef
Thank you.
If it's ok with you, can you add an MIT license to this repo? Great code, easy to follow, and well written. Love it.
I have a search term Input, so the infinite scroll is affected by that: when I change the criteria for that Input, I need all items to be cleared and re-fetch with the new criteria. How can I achieve that?
https://codesandbox.io/s/try-react-infinite-scroll-hook-4ekfj1?file=/src/App.jsx:1374-1384
rootMargin
without root
specifiedLittle rules of Interception Observer API
๏ผ
root
default to viewport while the viewport doesn't have any margin, so set rootMargin
to any value will always fallback to 0px
.
Here's my code below.
It doesnt trigger "nextPage" function, while I scroll down (at the bottom of page).
whats wrong?
const [infiniteRef] = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: nextPage,
disabled: !!error,
rootMargin: '0px 0px 400px 0px',
})
<div className="my-content" ref={infiniteRef}>
<div className="row" >
<div className="col-sm-12">
<div className="row">
{product_list.data.map((item, i) => (
<div className="col-md-3 col-sm-6 col-6">
<ProductCard {...item} />
</div>
))}
</div>
</div>
</div>
Hello!
Thank you for your work on this library. Doing a bit of due diligence before bringing it into a project.
Noticed a weird case involving error handling that causes an infinite loop.
To reproduce:
async function handleLoadMore() {
setLoading(true)
try {
// API fetch typically here, but forcing an error
throw 'Uh oh'
} catch (error) {
setError(true)
}
}
const infiniteRef = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: handleLoadMore,
scrollContainer,
});
If the function onLoadMore
encounters an error, it will continue getting called and enter an infinite loop.
After some trial and error, it seems like turning the loading off or setting hasNextPage
to false when an error is encountered prevents this:
async function handleLoadMore() {
setLoading(true)
try {
// API fetch typically here, but forcing an error
throw 'Uh oh'
} catch (error) {
setError(true)
setHasNextPage(false)
}
}
Curious if this is the preferred way to handle errors?
Wondering if the the library should handle this internally, so that if an error is raised this condition can no longer be met:
https://github.com/onderonur/react-infinite-scroll-hook/blob/master/src/useInfiniteScroll.ts#L127
Hi,
I having issue when integrate react-infinite-scroll-hook to React Typescript. I follow the code here https://codesandbox.io/s/react-infinite-scroll-hook-vwtr8?from-embed=&file=/src/InfiniteList.tsx:1965-1980
But it doesn't work on my project. I got this error:
for the code
<List ref={infiniteRef}>
I don't know how to fix it, can you help me?
Thank you
I'm migrating my remix app to be all ESM, my code was like this
import useInfiniteScroll from 'react-infinite-scroll-hook';
But now it produces error
TypeError: __vite_ssr_import_5__.default is not a function or its return value is not iterable
Stack pointing to my code:
import { default as useInfiniteScroll } from 'react-infinite-scroll-hook';
import * as useInfiniteScroll from 'react-infinite-scroll-hook';
No luck!
Hi,
Thanks for this project - it's very good and has been a big help!
I'm using it on a page with a big footer (below the infinite list) and so if you scroll fast you can end up below the sentry and load more is not triggered. You have to scroll back up and then down again.
You can recreate it on your demo (https://onderonur.github.io/react-infinite-scroll-hook/) by decreasing the vertical height of the browser window and then scrolling quickly down so that only the footer is visible.
It may be the intended way for the hook to work but I wondered if perhaps the logic for loading more could be if the sentry is intersecting or if it's below the current viewport?
Many thanks!
When I move to the bottom of the page in your demo then if the list items are not loaded, I have to move back to where the text "footer" is written and then it loads more item
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.