I have this component:
const PostsList = ( { id } ) => {
const { pages, size, setSize } = usePages( "/all-posts" )
return(
<div id={ id } className={ styles.PostsListContainer }>
{
pages?.map( ( { data } ) =>
data?.posts?.edges?.map( ( { node: post } ) =>
<PostCard key={ post?.id } title={ post?.title } />
)
)
}
<button onClick={ () => setSize(size+1)}>Load more</button>
</div>
)
}
export default PostsList
The usePages hook makes a Graphql request and returns pages, an array of objects, each object representing a page of results, which looks like this:
const pages = [
{
data: {
posts: {
edges: [
{ node: { id: 1 } },
{ node: { id: 2 } },
{ ... }
]
}
},
errors: [ ... ]
},
{
data: { ... },
errors: { ... },
}
]
Now, suppose that when fetching page 3 some error occurs, and data.posts is empty: how do I append an error message to the list?
I tried doing this:
const PostsList = ( { id } ) => {
const { pages, size, setSize } = usePages( "/all-posts" )
return(
<div id={ id } className={ styles.PostsListContainer }>
{
pages?.map( ( { data } ) => {
if( data?.posts ) {
return data?.posts?.edges?.map( ( { node: post } ) =>
<PostCard key={ post?.id } title={ post?.title } />
)
} else {
return <p>Error when fetching the posts</p>
}
})
}
<button onClick={ () => setSize(size+1)}>Load more</button>
</div>
)
}
export default PostsList
but sure enough the error message replaces the whole list, meaning even the previous pages which were successfully fetched. I can't either set a piece of state to use as a flag and update it in the render method when data.posts is empty, 'cause that creates the "too many re-renders" error.