Reputation: 539
Well I already knew that we should do something like this to keep the state up to date with firebase changes.
import FirebaseRef from '...'
.
.
.
class MyComponent extends React.Component {
state = {
maxVotes: 0
}
componentDidMount() {
const { boardId } = this.props
FirebaseRef.child(`boards/${boardId}/maxVotes`).on('value', snapshot => {
this.setState({maxVotes: snapshot.val()})
})
}
But my habit of coding is to delegate API call in other file and import it to component. Can I do something like this?
import { setMaxVotes } from ...
.
.
.
componentDidMount() {
const { boardId } = this.props
setMaxVotes(boardId)
}
And how does the setMaxVotes method looklike ? Should I complicate thing like this, or it's not best pratice?
Upvotes: 0
Views: 40
Reputation: 16482
It is common to delegate API calls to different modules but setting the react component state in different module is not a best practice. So you can create different module for API calls but you should set the state in component itself. The code may look something like this
componentDidMount() {
const { boardId } = this.props
setMaxVotes(boardId, 'value', snapshot => {
this.setState({maxVotes: snapshot.val()})
})
}
setMaxVotes(boardId, eventType, cb) {
FirebaseRef.child(`boards/${boardId}/maxVotes`).on(eventType, cb);
}
Upvotes: 2