1
votes

I'm trying to use a json file which contains multiple arrays in my Next.js app. My json file is a little complicated so I'm not exactly sure how to go about converting it into an object usable by the getStaticPaths function. I'm getting the following error message:

Error: A required parameter (id) was not provided as a string in getStaticPaths for /planets/[id]

Here's the code for my [id].js file:

import { useRouter } from 'next/router'
import Head from 'next/head'

export default function Planet({ planet }) {
    const router = useRouter()
    const { id } = router.query

    return (<>
    <Head>
        <title>{planet.name}</title>
    </Head>
    <h1>Hello {id}</h1>
    <h2>HHHHHHH</h2>
    </>)
}

export async function getStaticPaths() {
    const json = await import('https://api.jsonbin.io/b/600c5ab8bca934583e40b908').default;
    const bodies = await json.json()

    const paths = bodies.planets.map(planet => ({ 
        params: { id: planet.id.toString() },
    }));

    return {
        paths,
        fallback: false
    }
}

export async function getStaticProps({params}) {
    const json = await import('https://api.jsonbin.io/b/600c5ab8bca934583e40b908').default;
    const bodies = await json.json()

    return {
        props: {
            bodies
        }
    }
}

My JSON file is in this structure:

{
    "stars": [
        {
        "name": "Sun",
        "id": 1,
        .....
        }
    ],
    "planets": [ 
    {
        "name": "Mercury",
        "id": 1,
        .....
    }
    ],
    "moons": [  
    {
        "name": "Moon",
        "id": 1,
        .....
    }
    ]
}

Thanks for the help

1

1 Answers

0
votes

I think you mistake await import(...).default instead of await fetch(...) and your I can't find bug in your code. However, Your file code with name is [id].js, isn't it?

import { useRouter } from "next/router";
import Head from "next/head";

export default function Planet({ planet }) {
  const router = useRouter();
  const { id } = router.query;

  return (
    <>
      <Head>
        <title>{planet?.name}</title>
      </Head>
      <h1>Hello {id}</h1>
      <h2>HHHHHHH</h2>
    </>
  );
}

export async function getStaticPaths() {
  const json = await fetch("https://api.jsonbin.io/b/600c5ab8bca934583e40b908");
  const bodies = await json.json();
  const paths = bodies.planets.map(planet => ({
    params: { id: planet.id.toString() }
  }));

  return {
    paths,
    fallback: false
  };
}

export async function getStaticProps({ params }) {
  console.log(params);
  const json = await fetch("https://api.jsonbin.io/b/600c5ab8bca934583e40b908");
  const bodies = await json.json();
  const { planets } = bodies;

  return {
    props: {
      planet: planets.find(planet => planet.id == params.id)
    }
  };
}