JCastillo
JCastillo

Reputation: 336

Class Component to Functional component

How do I convert this class component to a functional component? What I am trying to achieve is to subscribe and unsubscribe from firebase using useEffect()

class PostsProvider extends Component {
  state = { posts: [] }

  unsubscribeFromFirestore = null;

  componentDidMount = () => {
    this.unsubscribeFromFirestore = firestore
      .collection('posts')
      .onSnapshot(snapshot => {
        const posts = snapshot.docs.map(collectIdAndDocs);
        this.setState({ posts });
      });
  }

  componentWillUnmount = () => {
    this.unsubscribeFromFirestore();
  }

Upvotes: 0

Views: 53

Answers (1)

Zachary Haber
Zachary Haber

Reputation: 11017

This is how I'd convert your component. You'd useState() to create your posts state and then a useEffect is pretty straightforward to move. The main thing you'd want to make sure of is that your dependency array is correct for it so it doesn't subscribe and unsubscribe too often (or not often enough).

function PostsProvider(){
    const [posts,setPosts] = useState([]);
    useEffect(() => {
        const unsubscribeFromFirestore = firestore
        .collection('posts')
        .onSnapshot(snapshot => {
        const posts = snapshot.docs.map(collectIdAndDocs);
        setPosts(posts);
        });
        return () => {
            unsubscribeFromFirestore();
        }
    }, [])
}

Upvotes: 2

Related Questions