1
\$\begingroup\$

I've got the following component structure:

Component hierarchy:

<AdminBlogPostContainer>
  <AdminBlogPostPage>
    <BlogPostForm>

AdminBlogPostContainer.js

  • Contains all the functions to make the API calls, get posts from database, save posts, delete posts, upload images, etc. It also sets the loading and error states.

When I'm editing a blogPost, before rendering the <BlogPostForm/> I need to get the blogPost from the database (using the blog-post-slug from the route), store in the blogPost state object.

Note: This is a Single Page App and I'm using react-router-dom for client-side routing.

The way I'm currently doing is this:

I have an "action" function that handles the setting of the loading and error status.

function ACTION_getBlogPost()

async function ACTION_getBlogPost() {
    try {
      setLoading(true);
      setError(null);

      await getBlogPostFromFirestore(props.match.params.slug);

      setLoading(false);
    }
    catch(err) {
      console.log(err);
      setError(err);
      setLoading(false);
    }
  }

And that "action" function calls the actual function getBlogPostFromFirestore() that retrieves the blogPost.

function getBlogPostFromFirestore(slug)

function getBlogPostFromFirestore(slug) {
    return new Promise(async (resolve,reject) => {

      try {
        const querySnapshot = await firebase.firestore().collection('blog').where('slug','==',slug).get();
        const blogPostData = querySnapshot.docs[0].data();

        setFirestoreID(querySnapshot.docs[0].id);
        setBlogPost(blogPostData );

        resolve();
      }

      catch(err) {
        reject(err);
      }
    });
  }

QUESTION

I think I could still improve the readability on this code. Maybe keep the "action" function like it is, but change the getBlogPostFromFirestore to this:

function getBlogPostFromFirestore() {
  return 
    firebase.firestore().collection('blog').where('slug','==',slug).get()
    .then((querySnapshot) => {
      const blogPostData = querySnapshot.docs[0].data();
      setFirestoreID(querySnapshot.docs[0].id);
      setBlogPost(blogPostData);
    })
    .catch((err) => throw err);
}

What do you think? Which one is the best? Any other suggestions?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.