0

I am getting a very annoying Maximum call stack size exceeded. when loading data using <FlatList> and onEndReached. The onRefresh does not cause this. I presume this has to do with the <FeedList> re-rendering when I update the data.

Can someone help me fix this or at least point me in the right direction?

export function useFeedState() {
  const state = useState(feedState);
  const api = useApi();

  function loadPosts(clear = false) {
    api
      .request<{ posts: IPost[] }>('get', 'posts', { feed: state.feed.value })
      .then((data) => {
        state.posts.set(
          clear ? data.posts : [...state.posts.value, ...data.posts]
        );
      })
      .catch((error) => {
        console.log(error);
      });
  }
  // ...
}

Component:

export default function FeedList() {
  const feedState = useFeedState();

  return (
    <FlatList
      data={feedState.posts}
      renderItem={({ item }) => <PostSlide post={item} />}
      keyExtractor={(item) => item.id.toString()}
      refreshing={feedState.isLoading}
      onRefresh={() => feedState.loadPosts(true)}
      onEndReached={() => {
        feedState.loadPosts();
      }}
    />
  );
}
Fredrik
  • 3,027
  • 8
  • 33
  • 66

1 Answers1

0

I solved this by using a callback in the set-method. Hookstate is built upon Reacts state and therefor has some similarities. You can read more about when to use a callback here.

// works
state.posts.set((prev) => {
  return clear ? data.posts : [...prev, ...data.posts];
});

// also works
clear ? state.posts.set(data.posts) : state.posts.merge(data.posts);

// doesn't work
state.posts.set(
  clear ? data.posts : [...state.posts.value, ...data.posts]
);

I guess maybe the reason for the loop was caused by using the value of the same state I was updating.

Fredrik
  • 3,027
  • 8
  • 33
  • 66