Reputation: 217
Problem: I want to create an admin page where a user can create new posts, this site shall also show the already published posts of that user. To get the already published posts I am running a firestore query - when I log the data of the query I get the correct posts, however they are logged twice. Now I need help finding out what causes my function to execute twice?
Admin Page
const getUserPostsWithID = async (userID) =>{
const q = query(collection(db,`users/${userID}/posts`));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
}
//TODO fix double execution of getUserPostsWithID
export default function AdminPage() {
const {userID} = useContext(authContext);
const posts = getUserPostsWithID(userID);
return (
<Authcheck>
<h1>The Admin Page</h1>
<PostList></PostList>
</Authcheck>
);
}
function PostList() {
return <PostFeed></PostFeed>;
}
Context Component
export const authContext = createContext({
user: "null",
username: "null",
userID: "null",
});
export default function AuthenticationContext(props) {
const [googleUser, setGoogleUser] = useState(null);
const [username, setUsername] = useState(null);
const [userID, setUserID] = useState(null);
useEffect(() => {
const getUsername = async (uid) => {
const docRef = doc(db, `users/${uid}`);
const docSnap = await getDoc(docRef);
console.log("Database Read Executed");
if (docSnap.exists()) {
setUsername(docSnap.data().username);
} else {
setUsername(null);
}
};
onAuthStateChanged(auth, (user) => {
if (user) {
setGoogleUser(user.displayName);
setUserID(user.uid);
getUsername(user.uid);
} else {
setGoogleUser(null);
}
});
}, []);
return (
<authContext.Provider value={{ user: googleUser, username: username , userID: userID}}>
{props.children}
</authContext.Provider>
);
}
Thank you for your help, it is very appreciated! :)
Upvotes: 0
Views: 432
Reputation: 217
useEffect(() => {
const getUserPostsWithID = async (userID) => {
const q = query(collection(db, `users/${userID}/posts`));
const querySnapshot = await getDocs(q);
console.log("Database Read Executed");
const postArr = [];
querySnapshot.forEach((doc) => {
postArr.push(postToJSON(doc));
});
setPostState(postArr);
};
getUserPostsWithID(userID);
}, []);
This code now prevents double execution even though I am not quite sure why.
Upvotes: 1