I have some .json files. I need to show all the data from the first .json file in browser as lazy loading.I need to make API call to the second .json when all contents are loaded from the first .json file (when user scoll to end of the page). I should not make all API call at a time. How to do this using react js.
Asked
Active
Viewed 2,428 times
2
-
Please include the code you have written so far and explain what you are having issues with. – Tholle Aug 06 '18 at 12:51
2 Answers
3
Make use of javascript scroll
eventListener and calculate the window scroll height in order to trigger the async call.
Please bind the necessary method in the constructor and define state respectively. Here is the code
componentDidMount(){
if(this.state.newData.length === 0){
window.addEventListener('scroll', this.handleOnScroll);
this.doQuery(1).then(res=>
this.setState({
newData: this.state.newData.slice().concat(res),
requestSent: false
}))
}
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleOnScroll);
}
handleOnScroll(){
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
var clientHeight = document.documentElement.clientHeight || window.innerHeight;
var scrolledToBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight;
if (scrolledToBottom) {
this.setState({
scrollCounter: this.state.scrollCounter + Math.floor(scrolledToBottom)
},()=>{
if(this.state.scrollCounter<4){
this.doQuery(this.state.scrollCounter).then(res=>
(res===BUSY)
? false
: this.setState({
newData: this.state.newData.slice().concat(res)
})
)
.catch(err=>this.setState({requestSent: false}))
this.setState({requestSent: true});
}else{
return true
}
})
}
}

CodeZombie
- 2,027
- 3
- 16
- 30
-
-
-
Not yet @karthik . there is a another problem. https://stackoverflow.com/questions/51719911/cant-load-local-files-dynamically-in-react-js – Gmv Aug 07 '18 at 06:19
0
React.js is just plain javascript with JSX flavour. You have to add the event scroll on your container and trigger a method to make a GET call on your API when scroll reaches end exactly as outside React.

Mosè Raguzzini
- 15,399
- 1
- 31
- 43