sociolog
sociolog

Reputation: 101

getDocs function does not work in first run

I try to get all docs from Firebase when user connect from localhost:3000/ (it automatically redirects to /profile) but it does not work in the first run. Then when the page is refreshed by a user, it works. How can I run it in first try? Code below:

 try {
    const querySnapshot = await getDocs(collection(db, "links"));
    await querySnapshot.forEach((doc) => {
      if (stUser.uid == doc.data().uid) {
        links.push(doc.id);
      }
    });
  } catch (e) {
    console.log(e);
  }

Redirects:

 function first() {
  if (!isLoggedIn.isLoggedIn) return <Redirect to="/auth" />;
     }
    function second() {
    if (isLoggedIn.isLoggedIn) return <Redirect to="/profile" />;
     }
    return (
    <div>
  <Route exact path="/">
    <Redirect to="/auth" />
   </Route>
   {handleRoute(images)}
   <Route path="/auth" component={Dashboard}>
    {second()}
   </Route>
   <Route  strict path="/profile" component={HomePage}>
    {first()}
   </Route>
 </div>
 );

Upvotes: 2

Views: 563

Answers (1)

Rafael Lemos
Rafael Lemos

Reputation: 5819

The problem here is that you are not setting this variable in your state, as mentioned by Frank in the comments, so whatever changes you make to this variable might not be refreshed until actually force them by refreshing the page. I recommend you try something like the following code:

const updatedArray = links;
await querySnapshot.forEach((doc) => {
  if (stUser.uid == doc.data().uid) {
    updatedArray.push(doc.id);
  }
});
setLinks(updatedArray);

Also, you will need to set this earlier in your code:

const [cars, setLinks] = useState([]);

finally, I would recommend you to check this documentation for a useState deepdive.

Upvotes: 1

Related Questions