I am very new to Next.js and could not get the getStaticProps
to work correctly.
import firebase from '../firebase'
export default function Home({ posts }) {
return (
<div>
<h1>All Posts</h1>
{posts.map((post) => (
<div key={post.pid}>{post.title}</div>
))}
</div>
)
}
export const getStaticProps = async () => {
let posts = []
firebase
.firestore()
.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.data().title)
console.log(doc.data().pid)
posts.push({
pid: doc.data().pid,
title: doc.data().title,
})
})
console.log(posts)
})
.catch(function (error) {
console.log('Error getting documents: ', error)
})
return {
props: {
posts,
},
}
}
When I console.log(posts)
in getStaticProps
, I can see the posts but somehow it is not display in the Home ponent. Any help would be greatly appreciated.
I am very new to Next.js and could not get the getStaticProps
to work correctly.
import firebase from '../firebase'
export default function Home({ posts }) {
return (
<div>
<h1>All Posts</h1>
{posts.map((post) => (
<div key={post.pid}>{post.title}</div>
))}
</div>
)
}
export const getStaticProps = async () => {
let posts = []
firebase
.firestore()
.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.data().title)
console.log(doc.data().pid)
posts.push({
pid: doc.data().pid,
title: doc.data().title,
})
})
console.log(posts)
})
.catch(function (error) {
console.log('Error getting documents: ', error)
})
return {
props: {
posts,
},
}
}
When I console.log(posts)
in getStaticProps
, I can see the posts but somehow it is not display in the Home ponent. Any help would be greatly appreciated.
1 Answer
Reset to default 6The problem is that you are not waiting for the promise returned from get()
to plete, thus returning an empty posts
(you only fill that variable after the promise returrns, on the then
part). In fact, if you put the console.log(posts)
right before the return (instead of on the then
part of the observable), you'll see it's empty there.
So you just need to await
it... something like (obviously untested):
export const getStaticProps = async () => {
let posts = []
try
{
// await the promise
const querySnapshot = await firebase
.firestore()
.collection('posts')
.orderBy('createdAt', 'desc')
.get();
// "then" part after the await
querySnapshot.forEach(function (doc) {
console.log(doc.data().title)
console.log(doc.data().pid)
posts.push({
pid: doc.data().pid,
title: doc.data().title,
})
})
console.log(posts)
} catch(error) {
// catch part using try/catch
console.log('Error getting documents: ', error)
// return something else here, or an empty props, or throw an exception or whatever
}
return {
props: {
posts
}
}
}