I have a Next.js application with the following page:
import { useState, useEffect } from 'react';
import axios from 'axios';
import { withRouter } from 'next/router';
import NotFound from '@/pages';
import { Page, PostBlock } from '@/components';
const Main = ({ router }) => {
const [postsData, setPostsData] = useState({ posts: [], page: 0, pages: 0 });
function fetchData() {
axios
.get('/api/articles', {
params: {
page: router.query?.page,
lang: router.locale,
tag: router.query.tag,
},
})
.then(response => {
setPostsData(response.data);
})
.catch(error => console.log(error));
}
useEffect(() => {
fetchData();
}, []);
// if (!postsData.posts.length) return <NotFound />;
return (
<Page title='Home' className='home-template'>
<div id='grid' className='post-grid'>
{postsData.posts?.map(post => {
return (
<PostBlock
featured={post.featured}
key={post.key}
/>
);
})}
</div>
</Page>
);
};
export default withRouter(Main);
The api fetches some articles on component mount, and display them in the UI. So far so good.
I also want to display a component in case there are no articles to display or if the api fails, but if I uncomment the line
if (!postsData.posts.length) return <NotFound />;
the application ends up in an infinite loop.
How can I fix this?