0

I am working on a React blog app and have posts in markdown files with metadata. The metadata is stored in Firestore. The .md files with the content are stored in Cloud Storage. The App component uses useEffect get the metadata for each post from Firestore and save it (an array of objects) into PostContext. This is the App component:

import React, { useEffect } from 'react'
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"
import { firestore } from './firebase'
import { usePostsUpdate } from "./contexts/PostContext"
import PrivateRoute from "./components/auth/PrivateRoute"
...

function App() {
  const savePosts = usePostsUpdate()

  useEffect(() => {
    const postsRef = firestore.collection('metadata')
    postsRef.get()
      .then((snapshot) => {
        const posts = snapshot.docs.map((doc) => ({
          ...doc.data()
        }))
        posts.sort((a, b) => b.postId - a.postId)
        savePosts(posts)
        console.log('App: in useEffect, posts.length', posts.length)
      })
  }, [])

  console.log('APP')
  return (
    <React.Fragment>
      <Router>
        <Switch>
          <Route exact path="/" component={Home} />
          ...
          <Route path="/all-posts" component={AllPostsPage} />
          <Route path='/post/:id' render={props => <Post {...props} />} />
          <Route path='/404' component={NotFoundPage} />
        </Switch>

      </Router>
    </React.Fragment>
  );
}

export default App;

There are 2 issues. First, regarding context. The 'savePost()' function is saving the array to PostContext, which is being used in the home and 'all-posts' pages successfully. But, when I try a '/post/:id' to access a specific post, the array pulled in from PostContext is empty. Somehow, it seems that the array is being reset to it's default (empty) value, so there are errors when I try to access it (the array holds the urls to access the markdown files in Cloud Storage that are needed to retrieve the content needed on the page). I can't find a reason for this to happen.

Second, React is telling me to include 'savePosts' as a dependency in useEffect. But when I do that, it just loops. The same thing happens if I remove the dependency array (which I don't really want to do). There is no dependency I can add that satisfies React and doesn't loop continuously.

Fruno
  • 81
  • 10

1 Answers1

0

Now it works. I was entering urls manually to test the routing. I went ahead and set up dynamic routing (routing to /post/id by clicking on a post summary on the home page), and now the array in context is populated properly. I don't understand why manually entering 'localhost:3000/post/1' in the browser works differently than routing to the same URL by clicking on a link, but it does.

That didn't solve the issue with the React useEffect warning, but I can live with that.

Fruno
  • 81
  • 10