Pagination in Live Object - Typescript

HI,
I am fetching user’s post on user page. I am using PostRepository.getPosts with subscribePostTopic for live object implementation.
Here is my code:

useEffect(() => {
        if (user) {
      const targetType = 'user';
      const targetId = user.userId;

      const unsubscribe = PostRepository.getPosts(
        { targetId, targetType, limit: 20, sortBy: 'lastCreated' },
        ({ data: posts, onNextPage, hasNextPage, loading }) => {
          setLoading(loading);
          if (hasNextPage) {
            setHasMoreData(true);
            
          } else {
            setHasMoreData(false);
          }
          setPosts(posts);
          subscribePostTopic(targetType, user as any);
        }
      );
      disposerPosts.push(unsubscribe);
      return () => {
        disposerPosts.forEach((fn) => fn());
      };
    }
  }, [user, userId]);

Please suggest me a way to implement onNextPage when user scroll down to the page.
How can i access onNextPage function outside useeffect? or suggest me some other way to implement this.

Hey @ahmedsakri,

You could use it outside the same way you have access to loading, posts etc.
Has that not worked?

If not, could you explain what errors are you getting?

Kind regards,
Cijin

How can i use it outside? you mean outside of useEffect?
Can you give me example of doing it?

@ahmedsakri You can use useState to store the object and use variables/function outside useEffect. Here is the code example.

const [postCollection, setPostCollection] = useState<Amity.LiveCollection<Amity.Post<any>>>()
const { data: posts, onNextPage, hasNextPage, loading } = postCollection ?? {}

  useEffect(() => {
    if (user) {
  const targetType = 'user';
  const targetId = user.userId;

  const unsubscribe = PostRepository.getPosts(
    { targetId, targetType, limit: 20, sortBy: 'lastCreated' },
    (data) => {
      setPostCollection(data)
      subscribePostTopic(targetType, user as any);
    }
  );
  disposerPosts.push(unsubscribe);
  return () => {
    disposerPosts.forEach((fn) => fn());
  };
}
1 Like