Here is my Console with console logged values.
Home Page is called 4 times i dont know why and Cards.js is also called even if i am checking for loading.
Here is my Home.js Code. I have tried removing dependency from effect hook but didn't worked.
const Home = () => {
console.log('Home Page');
const dispatch = useDispatch()
const loading = useSelector(state => state.idFor.loading)
const currentPage = useSelector((state) => state.idFor.currentPageHome)
const homePosts = useSelector((state) => state.posts)
useEffect(() => {
console.log('Home effect');
dispatch(setLoading(true))
dispatch(getAllPosts(currentPage))
}, [dispatch, currentPage])
return (
loading ? (
<Loader type="ThreeDots" color="#000000" height={500} width={80} />
) : (
<Cards posts={homePosts} setCurrentPage={setCurrentPageHome} currentPage={currentPage} pageName={"LATEST"} />
)
)
}
Here is my Cards.js code
const Cards = ({ posts, setCurrentPage, currentPage, pageName }) => {
console.log('Cards.JS called', posts);
const dispatch = useDispatch()
if (posts.length !== 0) {
dispatch(setLoading(false))
}
const handleNextPage = () => {
dispatch(setLoading(true))
dispatch(setCurrentPage(currentPage + 1))
}
const handlePreviousPage = () => {
dispatch(setLoading(true))
dispatch(setCurrentPage(currentPage - 1))
}
return (
<div className="container">
<h4 className="page-heading">{pageName}</h4>
<div className="card-container">
{
posts.map(post => <Card key={post._id} post={post} />)
}
</div>
<div className="page-div">
{currentPage !== 1 ? <span className="previous-page" onClick={handlePreviousPage}><</span>
: null}
<span className="next-page" onClick={handleNextPage}>></span>
</div>
</div>
)
}
The problem is from redux state.
const loading = useSelector(state => state.idFor.loading)
const currentPage = useSelector((state) => state.idFor.currentPageHome)
const homePosts = useSelector((state) => state.posts)
When the redux state is updated, the Home component is called.
The each component is synced with redux state.
Thank you.
contact me here if you want learn more