'Iterating object from getStaticProps and displaying in component template
I am trying to display the results for a database fetch that occured withing getStaticProps
but when I map the object in the component template I get the following errors. I would like to display all the data from the returned data.
My code:
import React from "react"
import { GetStaticProps } from "next"
// pages/index.tsx
import prisma from '../lib/prisma'
export const getStaticProps: GetStaticProps = async () => {
const tracks = await prisma.tracks.findMany();
return { props: { tracks } };
};
const Tracks = ({ tracks }) => {
console.log(tracks)
return (
<div>
<h1>All Tracks</h1>
{tracks.map((track ) => (
<div>{track.ts}</div>
))}
</div>
);
}
export default Tracks;
Error:
Unhandled Runtime Error
Error: Objects are not valid as a React child (found: Sat Jun 27 2020 17:43:15 GMT-0500 (Central Daylight Time)). If you meant to render a collection of children, use an array instead.
Here is what the response looks like:
Solution 1:[1]
track.ts
is a Date
type and basically is an object
. You can't just render the Date
object inside JSX. You need to convert it to string or number, for example:
const Tracks = ({ tracks }) => {
console.log(tracks)
return (
<div>
<h1>All Tracks</h1>
{tracks.map((track ) => (
<div>{String(track.ts)}</div>
))}
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Danila |