Passing array of objects to function adds to array
Hello, I need help to understand what going on here.
in page.tsx (server component) return:
<p>{JSON.stringify(expensesChartData)}</p>
<SummaryBarChart data={expensesChartData} />
in exported function SummaryBarChart(data) (client component) return:
<p>{JSON.stringify(data)}</p>
result:
[{"category":"myCatergory","amount":-6394},...]
{"data":[{"category":"myCatergory","amount":-6394},...]}
I could understand that the function sees the input as an object and calls the content data, since that's what I called the variable. But it didn't act this way before.
Before page.tsx was a client component and what is now the SummaryBarChart component was directly in page.tsx. Then I could just use data={expensesChartData} and no {"data": ... } was added.
Can I somehow make the recieved input just to be [{"category":"myCatergory","amount":-6394},...] or should I just change the component to handle the {"data": ... } part?
Am I doing something wrong/not best practice? Yes, I'm a beginner.
2 comments · 28% upvoted · other discussions
Thank you for reading. ChatGPT helped me. I guess I need to learn more basics..
Pevio1024 1 points · Feb 2024
ChatGPT is correct. It's conventional call the variable `props` in a component. That way, `props = {data: [...]}` and you can call `JSON.stringify(props.data)`. If another property was passed into `SummaryBarChart`, it wouldn't also be called `data`, it should have another name.