0

I imported a json file into my react app (using next.js router), and need to access a field in it by a parameter in the URL. It works when I navigate from another page (/home -> /annotations/<some id>), but doesn't work when I refresh the page (/annotations/<some id>) or directly access it.

JSON:

{
  "page1-9.svg": {
    "points": [
      ...
    ],
    "viewBox": "0 0 191.2066944434739 163.20512234635925"
  },
...
}
import tangrams from "../../assets/tangrams.json";
//..other imports

export default function Annotations(props) {
  const classes = useStyles();
  const router = useRouter();
  const { tangramId } = router.query;

  console.log(tangrams[tangramId]); // this always works
  console.log(tangrams[tangramId]["viewBox"]); // server error: TypeError: Cannot read property 'viewBox' of undefined
  return (...

If I only access tangrams[tangramId], it works fine, but if I access tangrams[tangramId]["viewBox"], it throws server error: TypeError: Cannot read property 'viewBox' of undefined.

Any idea why this happens?

guckmalmensch
  • 973
  • 2
  • 9
  • 22
  • What is the value of `router.query`? If it is not `"page1-9.svg"` then that would be your issue. – Mr. Polywhirl Jun 14 '21 at 18:14
  • 1
    As `useRouter()` is a hook `router.query` will be undefined when rendering on the server-side. Move the logic where you use `tangramId` to a `useEffect` instead. – juliomalves Jun 15 '21 at 23:39

1 Answers1

0

Searched around, seems to be related to this: github.com/vercel/next.js/discussions/11484

The query parameter is undefined at the first render...

guckmalmensch
  • 973
  • 2
  • 9
  • 22