Reputation: 155
I'm trying to map a json object in a nextjs class component with data coming from prisma. I stringify the data coming from prisma, else I get a serialization error on the date parameter.
I understand I cannot .map this.props.comments2, but how do I achieve what I am trying to do in the correct way?
Getting data:
Index.tsx:
export default function Home({ comments2 }) {
...
}
export async function getServerSideProps() {
console.log("lol");
const comments = await prisma.casinoComment.findMany();
const comments2 = JSON.stringify(comments);
console.log(comments2);
return { props: { comments2 } };
}
Component/List.tsx:
interface IProps {
comments2: [
{
content: string;
}
];
}
export default class FeaturedCasinos extends React.Component<
IProps,
IState,
{ country: String; flag: String }
> {
constructor(props: IProps) {
super(props);
}
render() {
return {
<>
{this.props.comments2.map((comment, index) => {
comment.content;
})}
</>
}
}
...
}
Json object:
[
{
"id": 1,
"casinoId": 1,
"content": "test",
"reply": false,
"parentId": 0,
"approved": false,
"likes": 3,
"createdAt": "2021-11-21T19:47:56.387Z",
"updatedAt": "2021-11-21T19:47:56.387Z",
"authorId": "ckw87a0r50008hvpvas31ow8k"
},
{
"id": 2,
"casinoId": 1,
"content": "test",
"reply": false,
"parentId": 0,
"approved": false,
"likes": 3,
"createdAt": "2021-11-21T19:52:07.427Z",
"updatedAt": "2021-11-21T19:52:07.427Z",
"authorId": "ckw87a0r50008hvpvas31ow8k"
}
]
Upvotes: 1
Views: 2356
Reputation: 155
I solved it...
Solution was to JSON.parse the comments after stringifying them:
const comments = await prisma.casinoComment.findMany();
const comments2 = JSON.stringify(comments);
const parsedComments = JSON.parse(comments2);
after this .map worked in the component, since you cant .map a pure string (which is not an array or object with the .map property)...
Upvotes: 1
Reputation: 921
Not 100% on your question but from the looks of it just change your jsx
This
<>
{this.props.comments2.map((comment, index) => {
comment.content;
})}
</>
to this
<>
{this.props.comments2.map((comment, index) => {
return(
<p>comment.content</p>
)
})}
</>
Upvotes: 1