ParseReact
ParseReact copied to clipboard
Cannot receive query data before rendering is done.
Hi,
I need to retrieve query and then with received data decide whether update the states. Weird thing is that i console log data retrieved from query in componentsDidMount() and receive an empty object, while adding the same log in the render() it prints me the object data.
How can I get query data and conditionally setState before I render?
constructor() {
super();
this.state = {
voteLabel: 'Vote +1',
disabled: false,
userVo: null
};
}
observe() {
return {
userVotes: (new Parse.Query('Vote'))
.equalTo('author', Parse.User.current())
};
}
componentDidMount() {
console.log(this.data.userVotes); //This always returns empty
if(isEmpty(this.data.userVotes)) {
console.log('Available to Vote');
} else {
this.setState({
voteLabel: 'Voted',
disabled: true
});
}
}
render() {
console.log(this.data.userVotes); //This one returns data
return ( ... )
}
Maybe it's just stupid mistake. Also, I was wondering how to incorporate promises to queries (cannot find examples with ES6).
Parse react triggers the query only when the component mounts so the data can't be ready at this point. Once the data is ready parse react triggers a forceupdate which then forces the component to render, and then the data is available.
I think in your case it might be better to manually run a regular parse query from componentDidMount. That way you have full controll over the handling of the data and simply set state in your callback.
Alternatively consider not using state at all. It seems that you can derive your state from the data. Just put the check you had in your componentDidMount in side your render function and let the component render according to what the data says?
I encountered a similar issue of needing the data object to set state. For us, componentDidUpdate() seemed to do the trick. That is called after the component's updates are flushed to the DOM. It happens after render(), but you can set state and re-render the component.