#Why let in docs?

1 messages · Page 1 of 1 (latest)

high oar
#

In the NextJs docs, there is an example of how to fetch data, that looks like this:

export default async function Page() {
  let data = await fetch('https://api.vercel.app/blog')
  let posts = await data.json()
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

Why are you using let instead of const here?

royal thornBOT
#

Hi @high oar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The use of let instead of const in the example you provided is not a recommended practice or a specific requirement of Next.js. In fact, the official Next.js documentation typically uses const for variable declarations that are not reassigned.

The example you've shared appears to be inconsistent with the current best practices. According to the Next.js Data Fetching documentation, a more up-to-date and correct version of this code would use const:

export default async function Page() {
  const data = await fetch('<https://api.vercel.app/blog'>)
  const posts = await data.json()
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

Using const is generally preferred when the variable is not going to be reassigned, which is the case in this example. The use of let in the example you found might be an oversight or an older version of the documentation.

It's always best to follow current JavaScript best practices, which include using const for variables that won't be reassigned, and let only for variables that will be reassigned later in the code.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: