I implemented infinite scrolling to my MERN app it works ok ,In addition to that I can also search specific item (instantly). If items match with search area text it automatically get data from server and display it on screen and i can paginate these search results also BUT when i clean search input area i can not use pagination function because "page" number (useState) automatically increased in the previous step. How can I handle this problem?
useEffect(() => {
const getData = async () => {
const { data } = await axios(
search
? `http://localhost:3003/api/product/pagination?page=0&search=${search}`
: `http://localhost:3003/api/product/pagination?page=0`
);
setData(data.posts);
};
if (search.length === 0 || search.length > 2) {
getData();
}
}, [search]);
const fetchPosts = async () => {
const { data } = await axios(
`http://localhost:3003/api/product/pagination?page=${page}&search=${search}`
);
return data.posts;
};
const fetchData = async () => {
const postsFromServer = await fetchPosts();
setData([...data, ...postsFromServer]);
if (postsFromServer.length === 0 || postsFromServer.length < 4) {
setHasMore(false);
}
setPage(page + 1);
};
return (
<>
<InfiniteScroll
dataLength={data.length} //This is important field to render the next data
next={fetchData}
hasMore={hasMore}
loader={<h4>Loading...</h4>}
>
<Container>
.map((item) => {
const {
_id,
kampaniyaName,
owner,
aboutProduct,
startDate,
endDate,
price,
category,
image,
} = item;
return (
<div key={item._id}>
<Card
_id={_id}
name={kampaniyaName}
company={owner}
about={aboutProduct}
date={timeLeft(startDate, endDate)}
price={price}
category={category}
image={image}
data={item}
/>
</div>
);
})}
</Container>
</InfiniteScroll>
</>
);
};
export default Home;