Reputation: 1100
I'm fetching Data from a Dribbble API. It is almost succefully but it is loading 12 shots from the API, and after this it is occurring a problem by repeating the same 12 again and then it after this it is loading the others in a right way: 13,14,15...
The shots' return: 1,2,3,4,5,6,7,8,9,10,11,12. OK RIGHT 1,2,3,4,5,6,7,8,9,10,11,12. repetition problem!!! WRONG 13,14,15,16... OK RIGHT
What is the solution for this undesirable repetition?
Here is the code:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Waypoint from 'react-waypoint';
import Dribbble from './Dribbble';
export default class Dribbbles extends Component {
constructor(props) {
super(props);
this.state = { page: 1, shots: [] };
this.getShots = this.getShots.bind(this);
}
componentDidMount() {
this.getShots();
}
getShots() {
return $.getJSON('https://api.dribbble.com/v1/shots?page='+ this.state.page + '&access_token=ACCESS_TOKEN_HERE&callback=?')
.then((resp) => {
var newShots = this.state.shots.concat(resp.data);
this.setState({
page: this.state.page + 1,
shots: newShots
});
});
}
render() {
const shots = this.state.shots.map((val, i) => {
return <Dribbble dados={val} key={i} />
});
return (
<div>
<ul>{shots}</ul>
<Waypoint
onEnter={this.getShots}
/>
</div>
);
}
}
Upvotes: 0
Views: 42
Reputation: 26
I think the onEnter event from your Waypoint
component is triggered unexpectedly, which has caused the getShots() function being called multiple times.
My suggestion is to specify a dataFecthed
state to control whether the Waypoint component mount or not.Just like below:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Waypoint from 'react-waypoint'
import Dribbble from './Dribbble'
export default class Dribbbles extends Component {
constructor(props) {
super(props)
this.state = { page: 1, shots: [], dataFetched: true }
this.getShots = this.getShots.bind(this)
}
componentDidMount() {
this.getShots()
}
getShots() {
this.setState({
dataFetched: false,
})
return $.getJSON(
'https://api.dribbble.com/v1/shots?page=' +
this.state.page +
'&access_token=41ff524ebca5e8d0bf5d6f9f2c611c1b0d224a1975ce37579326872c1e7900b4&callback=?'
).then(resp => {
var newShots = this.state.shots.concat(resp.data)
this.setState({
page: this.state.page + 1,
shots: newShots,
dataFetched: true,
})
})
}
render() {
const shots = this.state.shots.map((val, i) => {
return <Dribbble dados={val} key={i} />
})
return (
<div>
<ul>{shots}</ul>
{this.state.dataFetched && <Waypoint onEnter={this.getShots} />}
</div>
)
}
}
Upvotes: 1