Home > Blockchain >  Code that somehow accesses docs from firebase and displays contents that I don't understand? RE
Code that somehow accesses docs from firebase and displays contents that I don't understand? RE

Time:12-09

The function of the code is supposed to get the docs of the collection called posts and then output the post component that I created for each doc inside it. This is the code:

function AllPostsPage(props) {

    const postsRef = firestore.collection("posts");
    const query = postsRef.orderBy("createdAt", "desc");

    const [posts] = useCollectionData(query, {idField: "id"});

    return (

        <ThemeProvider theme={props.theme}>

            {posts && posts.map((title, desc, poster, imgUrl, comments) =>  <Post theme={props.theme} key={title.id} title={title} desc={desc} poster={poster} imgUrl={imgUrl} comments={comments} />)}

        </ThemeProvider>

    );

}

I would like to understand this code as I would have initially just done:

function AllPostsPage(props) {

    const posts = firestore.collection("posts");

    return (

        <ThemeProvider theme={props.theme}>

            {posts.get().then((result) => { result.docs.forEach((post) => {<Post title={post.data().title} ...otherData />} ) } )}

        </ThemeProvider>

    );

}

CodePudding user response:

I'm not a ReactJS expert, but an .orderBy() is used to specify the sort order of your data and by default, a query retrieves all documents that satisfy the query in ascending order by document ID. In the first code snippet you've posted, it means that the results of the query, will be printed in a descending order. Check this documentation for more information regarding order and limit data in firebase.

Additionally, useCollectionData hook has the following parameters:
query: (optional) firestore.Query for the data you would like to load, and; idField: (optional) name of the field that should be populated with the firestore.QuerySnapshot.id property.

Refer to this documentation for further instruction and guide in using Firestore with ReactJS.

  • Related