0

I tried a lot to get JSON data from API dynamics route to getStaticPaths using Next.js.

code:

pages/review/[id].js file

export async function getStaticPaths() {
  const res = await fetch('http://localhost:3000/api/hello');
  const items = await res.json();
  const paths = items.map((item) => ({
    params: { id: item.id.toString() },
  }));
  return { paths, fallback: false };
}

export async function getStaticProps(context) {
  const id = context.params.id;
  const res = await fetch(`http://localhost:3000/api/hello/${id}`);
  const item = await res.json();
  return {
    props: { item },
  };
};

data.json file

[
  {
    "id": 1,
    "title": "nice work",
    "image": "https://images.pexels.com/photos/13260611/pexels-photo-13260611.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
  },
  {
    "id": 2,
    "title": "good job",
    "image": "https://images.pexels.com/photos/13096525/pexels-photo-13096525.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
  },
  {
    "id": 3,
    "title": "hellow world",
    "image": "https://images.pexels.com/photos/12172737/pexels-photo-12172737.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
  }
]

pages/api/hello.js file

import data from '../../data.json';
export default function hello(req, res) {
  res.status(200).json(data);
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • What's the exact issue? what are you getting after using this code? – Pavan Nagadiya Sep 05 '22 at 05:09
  • You API route is at `/api/hello`, but you're making a request to `/api/hello/` in `getStaticProps` - that won't work. – juliomalves Sep 05 '22 at 18:19
  • However, you shouldn't even be making a request to your internal API route inside `getStaticProps`. You should use the API logic directly. See [Fetch error when building Next.js static website in production](https://stackoverflow.com/questions/66202840/fetch-error-when-building-next-js-static-website-in-production). – juliomalves Sep 05 '22 at 18:19

1 Answers1

1
// pages/posts/[id].js

// Generates `/posts/1` and `/posts/2`
export async function getStaticPaths() {
  return {
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    fallback: false, // can also be true or 'blocking'
  }
}

// `getStaticPaths` requires using `getStaticProps`
export async function getStaticProps(context) {
  return {
    // Passed to the page component as props
    props: { post: {} },
  }
}

export default function Post({ post }) {
  // Render post...
}

Reference Link https://nextjs.org/docs/basic-features/data-fetching/get-static-paths

AmirYousaf
  • 23
  • 4