英文:
Next.js 13: "Objects are not valid as a React child" error when fetching data with async/await
问题
Here's the translated code portion you requested:
async function getProducts() {
const { data } = await storefront(productsQuery);
return data.products;
}
export default async function Page({ params }: any) {
const fetchedData = await getProducts();
return (<>
{fetchedData.edges.map((item: any) => (
<Text>{item.node.title}</Text>
))}
</>);
}
And here's the translated data portion:
"data": {
"products": {
"edges": [
{
"node": {
"title": "Some title"
}
}
]
}
}
If you have any further questions or need assistance, please feel free to ask.
英文:
I am using Next.js 13 with the new app directory and I'm trying to fetch data from my API. But when i try using async/await i keep getting the error: "Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."
async function getProducts() {
const { data } = await storefront(productsQuery);
return data.products;
}
export default async function Page({ params }: any) {
const fetchedData = await getProducts();
return (<>
{fetchedData.edges.map((item: any) => (
<Text>{item.node.title}</Text>
))}
</>);
}
This is my code. The data I receive from the api is:
"data": {
"products": {
"edges": [
{
"node": {
"title": "Some title",
}
}
]
}
}
}
I've tried converting the title to a string using toString() and using a key attribute in the map function, but the error persists. Also, I have a 'use client'; at the top of each file since I'm using Chakra UI but this doesn't seem to be the source of the problem.
What am I doing wrong? How can I properly fetch and render the data in my Next.js app?
Thank you in advance for your help!
答案1
得分: 3
通过使用 async
关键字定义名为 Page
的函数组件,你在暗示该函数返回的是一个 Promise,而不是一个 React 组件。你的函数现在将 React 组件数组包裹在一个 Promise 中。函数组件无法返回 Promise。
英文:
By having the async
keyword function Page
which is a component you are implying that this function returns a promise rather than a react component.
Your function now wraps your result react component array inside a promise.
Functional components can't return promises.
答案2
得分: 2
你需要确保已获取的数据是可用的。例如:
export default function Page({ params }: any) {
const [fetchedData, setFetchedData] = useState([]);
useEffect(() => {
(async () => {
const data = await getProducts();
setFetchedData(data.edges);
})();
}, []);
return (<>
{fetchedData.edges.map((item: any) => (
<Text>{item.node.title}</Text>
))}
</>);
}
英文:
You need to make sure that the fetched data is available. For example:
export default function Page({ params }: any) {
const [fetchedData, setFetchedData] = useState([]);
useEffect(() => {
(async () => {
const data = await getProducts();
setFetchedData(data.edges);
})();
}, []);
return (<>
{fetchedData.edges.map((item: any) => (
<Text>{item.node.title}</Text>
))}
</>);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论