I am trying to load a list of 'Posts' from my firebase database into my react app. Specifically trying to set the state of my posts array.
constructor() {
super()
this.state = {
posts: []
}
}
componentDidMount() {
this.grabPosts()
}
grabPosts = () => {
const postList = firebase.db('posts').on('value', function(snapshot) {
snapshot.forEach((child) => {
console.log(child.val())
//Get child data
const childPost = child.val()
//Get copy of current state
const currentState = this.state.posts
//Push item into array
const newState = currentState.push(childPost)
//Update state
this.setState({
tasks: newState
})
})
})
}
Firebase Structure
posts
- (id)
- post-title
- post-image
..... etc etc
Im just trying to build an array of post objects so i can map through and create components for each post. However everytime I attempt to change my state I recieve the same error
Uncaught TypeError: Cannot read property 'state' of undefined
Can anyone point me in the right direction on where/how I am supposed to set the state of my posts