after I added this code I got blank page, nothing is loading. I guess that there is something wrong in componentWillReceiveProps but I don't know what exactly.
Also I have "Uncaught TypeError: this.state.postLists.map is not a function" in the console
import React, { Component } from 'react';
import { getDocs, collection, deleteDoc, doc } from "firebase/firestore";
import { auth, db } from '../firebaseconf';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
postLists: ''
}
}
setPostList = (newValue) => {
this.setState({
postLists: newValue
});
}
postsCollectionRef = collection(db, "posts");
componentWillReceiveProps = (nextProps) => {
if (nextProps.position !== this.props.position) {
const getPosts = async () => {
const data = await getDocs(this.postsCollectionRef);
this.setPostList(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getPosts();
}
}
deletePost = async (id) => {
const postDoc = doc(db, "posts", id);
await deleteDoc(postDoc);
};
render() {
return (
<div className="homePage">
{this.state.postLists.map((post) => {
return (
<div className="post"> {post.title} </div>
);
})}
</div>
);
}
}
export default Home;
CodePudding user response:
The root cause of your issue is here:
this.state = {
postLists: ''
}
You are defining postLists as a string, and using the array .map() method which is causing the error.
CodePudding user response:
Set initial value of postLists in state as array
this.state = {
postLists: []
}
And maybe its also good idea to add some ternary operator if there is no data something like:
{this.state.postLists.length ? this.state.postLists.map((post) => {
return (
<div className="post"> {post.title} </div>
);
}) : 'No data'}
Also think about replacing componentWillReceiveProps with componentDidUpdate because componentDidUpdate should now be used rather than componentWillReceiveProps
From React docs: https://reactjs.org/docs/react-component.html
