react-infinite-scroller icon indicating copy to clipboard operation
react-infinite-scroller copied to clipboard

On scroll function won't run If the initial data wasn't fetched

Open ghost opened this issue 5 years ago • 0 comments

Describe the bug I put a condition to fetch data only when it's the first time it's fetching data in component . So in useEffect I set an if statement to whenever the (!props.fetchedData) is empty or null , fetch data and it works perfectly the first time and the onScroll function works as well .

The problem is whenever I go to other routes and comeback with browser's back button , just because the fetchedData is not empty because useEffect has ran before so no need to fetch again , the onScroll function won't run when I scroll to the bottom of the page .

The onScroll function will only run whenever there was fetch data . It won't run if the first fetching didn't happen .

To Reproduce `import Axios from 'axios'; import React from 'react'; import { NavLink } from 'react-router-dom'; import InfiniteScroll from 'react-infinite-scroller'; import { callAction, fetch } from './redux/action'; import { connect } from 'react-redux';

function Posts(props) { const [ len, setLen ] = React.useState(null); const [ start, setStart ] = React.useState(0); const [ end, setEnd ] = React.useState(20);

React.useEffect(() => {
	if (!props.fetchedData) {
		Axios.get(`https://jsonplaceholder.typicode.com/posts`).then((res) => {
			setLen(res.data.length);
			const sliced = res.data.slice(start, end);
			props.fetch(sliced);
			setStart(end);
			setEnd((prev) => prev + 10);
			props.callAction(true);
		});
	}
}, []);

const onScroll = () => {
	Axios.get(`https://jsonplaceholder.typicode.com/posts`).then((res) => {
		setLen(res.data.length);
		const sliced = res.data.slice(start, end);
		const concated = props.fetchedData.concat(sliced);
		props.fetch(concated);
		setStart(end);
		setEnd((prev) => prev + 10);
	});
};

return (
	<div>
		<NavLink to="/other">Other</NavLink>
		<InfiniteScroll
			pageStart={0}
			loadMore={onScroll}
			hasMore={props.fetchedData && props.fetchedData.length < len}
		>
			{props.fetchedData &&
				props.fetchedData.map((each) => {
					return <div style={{ margin: '20px 0' }}>{each.id}</div>;
				})}
		</InfiniteScroll>
	</div>
);

} `

Expected behavior I expect onScroll function to run whenever the user reaches the end of the fetchedData no matter if there was initial data fetching or not .

Device (please complete the following information):

  • OS: Windows 8.1
  • Browser : chrome
  • Version : latest

ghost avatar Sep 27 '20 19:09 ghost