At the moment when 'scroll' is at the very bottom, the function getUsers () is called. How to set the scroll so that it doesn't reach the end of the slider, and the getUsers () function is called. That there would be an infinity scroll effect. I mean the scroll effect like here: https://codesandbox.io/s/ww7npwxokk. When the scroll reaches the bottom, it goes back.
Code here: https://stackblitz.com/edit/react-nq8btq
import './style.css';
import axios from 'axios';
class App extends Component {
constructor() {
super();
this.state = {
users: [],
page: 1
};
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
axios({
url: `https://jsonplaceholder.typicode.com/users`,
method: "GET"
})
.then(res => {
this.setState({
users: res.data
});
})
.catch(error => {
console.log(error);
})
}
scroll = (e) => {
const page = this.state.page;
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
alert('bottom');
this.getUsers()
this.setState({
page: this.state.page + 1
})
}
const top = e.target.scrollTop;
if(top === 0 && page > 1) {
alert('I AM AT THE TOP');
this.setState({
page: this.state.page - 1
})
}
}
render() {
console.log(this.state.page)
console.log(this.state.users)
return (
<div>
<div onScroll={this.scroll} className="container">
<ul>
{this.state.users.map((user, index) =>
<li>
{user.name}
</li>
)}
</ul>
</div>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Here I've updated your code, slightly simplified, but mostly your code with the key points commented.
class App extends Component {
state = {
users: [],
page: 1
};
componentDidMount() {
this.getUsers();
}
getUsers = () => {
axios({
url: `https://jsonplaceholder.typicode.com/users`,
method: "GET"
})
.then(res => {
this.setState({
// *you must append to users in state, otherwise
// the list will not grow as the user scrolls
users: [...this.state.users, ...res.data],
page: this.state.page + 1
});
})
.catch(error => {
console.log(error);
})
}
scroll = (e) => {
// *simplified, to only handle appending to the list
// note the 50px from the bottom, adjust as required
// so that the request is made before the users reaches
// the bottom of the page under normal scrolling conditions.
if (e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight + 50) {
this.getUsers();
}
}
render() {
return (
<div onScroll={this.scroll} className="container">
<ul>
{this.state.users.map((user, index) =>
// *always add a unique key for each item
<li key={user.name}>
{user.name}
</li>
)}
</ul>
</div>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With