Skip to content

Commit

Permalink
Update data-fetching.md to use async file loading (vercel#17518)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim Neutkens <[email protected]>
  • Loading branch information
DylanRJohnston and timneutkens authored Jan 23, 2021
1 parent caf95e1 commit 5baedf5
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions docs/basic-features/data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ Since Next.js compiles your code into a separate directory you can't use `__dirn
Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed.

```jsx
import fs from 'fs'
import { promises as fs } from 'fs'
import path from 'path'

// posts will be populated at build time by getStaticProps()
Expand All @@ -311,11 +311,11 @@ function Blog({ posts }) {
// direct database queries. See the "Technical details" section.
export async function getStaticProps() {
const postsDirectory = path.join(process.cwd(), 'posts')
const filenames = fs.readdirSync(postsDirectory)
const filenames = await fs.readdir(postsDirectory)

const posts = filenames.map((filename) => {
const posts = filenames.map(async (filename) => {
const filePath = path.join(postsDirectory, filename)
const fileContents = fs.readFileSync(filePath, 'utf8')
const fileContents = await fs.readFile(filePath, 'utf8')

// Generally you would parse/transform the contents
// For example you can transform markdown to HTML here
Expand All @@ -329,7 +329,7 @@ export async function getStaticProps() {
// will receive `posts` as a prop at build time
return {
props: {
posts,
posts: await Promise.all(posts),
},
}
}
Expand Down

0 comments on commit 5baedf5

Please sign in to comment.