I get the following error when mapping the state for my posts:[]
object
TypeError: this.state.posts.map is not a function
I looked at something similar but it didn't come close to resolving the problem.
The console.log() shows the current data, so the function works, it just a matter of passing the data within the posts:[]
object and mapping it.
{this.state.posts.map((post, key)=> {
return(
<div key={key}>
<h2>{post.description}</h2>
<small>{post.username}</small>
</div>
);
})}
Dashboard.js (updated)
class Dashboard extends Component{
constructor(props){
super(props)
this.state = {
username:"",
loading: true,
posts:{},
myArray:[]
}
}
componentWillMount(){
this.getPosts()
}
getPosts() {
const collection2 = fire.collection('posts');
collection2.get().then(snapshot => {
snapshot.forEach(doc => {
let items = doc.data();
// items = JSON.stringify(items);
this.setState({
posts: items
});
})
const eArray = Object.values(this.state.posts);
this.setState({
myArray:[...eArray]
})
console.log(this.state.myArray)
})
}
componentDidMount(){
if(this.props.userId){
const collection = fire.collection('users');
collection.get().then(snapshot => {
snapshot.forEach(doc => {
this.setState({
username: doc.data().username,
loading:false
})
});
});
}
}
render(){
if (!this.props.userId) return <Redirect to='/' />
const { loading, posts,myArray } = this.state;
if(loading){
return(
<div className="loader"></div>
)
}
return(
<div className="container">
<div className="row">
<div className="col-md-6 mt-3">
<h1>Welcome {this.state.username.toLowerCase()}</h1>
{myArray.map((post, key)=> {
return(
<div key={key}>
<h2>{post.description}</h2>
<small>{post.username}</small>
</div>
);
})}
</div>
</div>
</div>
);
}
}