Home > other >  NextJS not showing content from static json file
NextJS not showing content from static json file

Time:04-18

I'm relatively new to Next, but here is the issue. I've got a static JSON file which is in the root of my project directory and is as follows

{"data":[{"id":1,"attributes":{"name":"Test Product 1","content":"Stvarno ne znam sta bi dodao ovdje jer samo testiram","meta_description":"Opis koji moze da stoji u meti / SEO i to","meta_title":"Testni Product - Lion Kingdom","price":12.99,"slug":"test-product-1","createdAt":"2022-04-17T12:12:36.787Z","updatedAt":"2022-04-17T12:12:39.540Z","publishedAt":"2022-04-17T12:12:39.531Z"}},{"id":2,"attributes":{"name":"Test Product 2","content":"Jos jedan testni post da testiram producte v2","meta_description":"Neki opis za metu","meta_title":"Testni Product 2 - Lion Kingdom","price":49700,"slug":"test-product-2","createdAt":"2022-04-17T12:15:04.241Z","updatedAt":"2022-04-17T12:15:05.078Z","publishedAt":"2022-04-17T12:15:05.075Z"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":2}}}

Now I'm trying to pass it as a prop to use it on the website, but am not able to for some unknown reason, the compiler shows no errors but yet the div still shows up empty not fetching anything from the json. Here is how I set it up in next

Defining it up top

import products from '../products.json'

and then in the body


export default function index() {
  return (
    <div>
      <Head>
      <title> ECommerce Alpha</title>
      <link rel="icon" href="/favicon.ico" />
      </Head>

    {products.data.map(product => {
      <div key={product.attributes}>
       <div>{product.attributes.name}</div>
      </div>
    })}


    </div>
  )
}

The result is yet a blank page, if someone could point out why next is not fetching it statically from a file I would appreciate it :)

CodePudding user response:

You're seeing a blank page because your map()'s arrow function is missing an explicit return statement:

{products.data.map((product) => {
  // this is a block body (i.e., opened with a brace), so you need a `return`
  return (
    <div key={product.id}>
      <div>{product.attributes.name}</div>
    </div>
  );
})}

You can make the return implicit by not using braces:

{products.data.map((product) => (
  // group with parentheses instead
  <div key={product.id}>
    <div>{product.attributes.name}</div>
  </div>
))}
  • Related