0

I am receiving an error when trying to display a JSON record retrieved using SWR, but the record appears correctly when displayed to the console using console.log.

TypeError: Cannot read properties of undefined (reading 'name')

import useSWR from "swr";
const fetcher = (url) => fetch(url).then((res) => res.json());

export default function Index() {
  const { data, error } = useSWR("/api/staticdata", fetcher);

  if (error) return <div>Failed to load</div>;
  if (!data) return <div>Loading...</div>;
  console.log("data is: " + data);
  return (
    <div>
      <h1>My Framework from file</h1>
      <ul>
        <li>Name: {data.record.name}</li>
        <li>Language: {data.record.language}</li>
      </ul>
    </div>
  );
}

console.log shows

data is: {
    "record": {
        "id": 8221,
        "uid": "a15c1f1d-9e4e-4dc7-9c45-c04412fc5064",
        "name": "Next.js",
        "language": "JavaScript"
    }
}

This is a next.js application. I am using the code verbatim from https://vercel.com/guides/loading-static-file-nextjs-api-route.

Any help would be greatly appreciated!

HamletHub
  • 481
  • 1
  • 9
  • 19

1 Answers1

1

The data returned by useSWR is actually not a JSON object, but a string. When I used JSON.parse, I was able to display the data correctly.

...

    const obj = JSON.parse(data);
    return (
      <div>
        <h1>My Framework from file</h1>
        <ul>
          <li>Name: {obj.record.name}</li>
          <li>Language: {obj.record.language}</li>
        </ul>
       </div>
     );
   }
HamletHub
  • 481
  • 1
  • 9
  • 19