I have this code:
class App extends Component {
constructor(props){
super(props);
this.state = {
elements: [],
}
}
loadData = () => {
fetch('http://localhost:3001/')
.then(res => res.json())
.then(data => {this.setState({elements: data})})
.catch(err => console.log(err))
}
newElement = () => {
do {this.loadData()} while (/don't know what to put here/ === this.state.elements.length)
componentDidMount(){
this.loadData();
console.log(this.state.feladatok)
}
render() {
return (
<div className="App">
<Element newElem={() => this.newElement()}/>
</div>
);
}
}
//The Element component renders more Element components. All element component looks like this inside:
//<Element newElem={this.props.newelem} />
//If a new element has created, that will do two things:
//Adds a new element to the database
//The this.props.newElem() gets called
The situation is that the newElement is called from the children component's props just if a new component was created (and posted to the database). I need to wait until the server responds with the new data. The data comes as an array. (approximately 10ms, but i think it's better to wait the time). The code shown above is my idea to detect if the elements length isn't the same it was before. But if i create a new state, for an example elementsCounter(and set the empty value to 0), whatever where i set it to elements.length, it still remains 0. Or if i declare a variable into the newElement function, and set the value to this.state.elements.length, and after do the do...while, it creates an infinite loop. So how to solve this problem?
this.loadData()multiple times or are you using it to wait until the data was loaded ?newElementbeing used? I assume it's not repeatedly fetching data while the state isn't set...newElement. But it gets called before the server process the new element. And all the elements fetched inloadData. So i use the loop to fetch again and again until the function detects the change in the received data's length.newElementthat waits for the return ofloadDatabut it's hard to tell, the question and code are not clear.