admin管理员组文章数量:1425712
Hi I'm trying to learn how to use React with an API response. I have a GraphQL API endpoint that is returning information on products in JSON. I would like to loop over the response and render a react ponent for each product simply displaying the product name.
The JSON response looks like this:
{
"data": {
"products": [
{
"productName": "Pepsi",
"price": "1.99",
},
{
"productName": "Coke",
"price": "2.99",
},
// and so on...
]
}
}
I've successfully console logged each product name by doing the following (I'm using axios):
async function contactAPI() {
return await axios({
url: '',
method: 'post',
data: {
query: `
QUERY GOES HERE
`
}
})
}
async function goFetch() {
let resp = await contactAPI();
for (let entry in resp.data.data.products) {
console.log(resp.data.data.products[entry]['productName']);
}
}
But now I would like to render a react ponent for each product, but I keep getting the error Objects are not valid as a React child (found: [object Promise]).
Below is the code I'm using right now. How can I fix this so that I can return a react ponent for each product with the product name?
App.js
async function contactAPI() {
return await axios({
url: '',
method: 'post',
data: {
query: `
QUERY GOES HERE
`
}
})
}
async function App() {
let resp = await contactAPI();
return (
<div>
{resp.map(p => (
<div>
<ProductCard productName={p.productName} />
</div>
))}
</div>
);
}
ProductCard.js
function ProductCard(props) {
return (
<div>
<div>{props.productName}</div>
</div>
);
}
Edit: Based on Andy's suggestion, I tried using states and useEffect, but I'm getting two errors. The first one is Error: Objects are not valid as a React child (found: [object Promise]).
and the second one is Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function ponent.
The second error points to const [products, setProducts] = useState([]);
This is my current code:
async function App() {
const [products, setProducts] = useState([]);
useEffect(() => {
async function getData() {
const res = await contactAPI();
setProducts(res.data.data.products);
}
getData();
}, []);
return (
<div>
<div>
{products.map(p => (
<div>
<ProductCard productName={p.productName} />
</div>
))}
</div>
</div>
);
}
Edit 2: Fixed by removing the async
keyword from the original function App()
Hi I'm trying to learn how to use React with an API response. I have a GraphQL API endpoint that is returning information on products in JSON. I would like to loop over the response and render a react ponent for each product simply displaying the product name.
The JSON response looks like this:
{
"data": {
"products": [
{
"productName": "Pepsi",
"price": "1.99",
},
{
"productName": "Coke",
"price": "2.99",
},
// and so on...
]
}
}
I've successfully console logged each product name by doing the following (I'm using axios):
async function contactAPI() {
return await axios({
url: 'https://graphqlexample./api/products',
method: 'post',
data: {
query: `
QUERY GOES HERE
`
}
})
}
async function goFetch() {
let resp = await contactAPI();
for (let entry in resp.data.data.products) {
console.log(resp.data.data.products[entry]['productName']);
}
}
But now I would like to render a react ponent for each product, but I keep getting the error Objects are not valid as a React child (found: [object Promise]).
Below is the code I'm using right now. How can I fix this so that I can return a react ponent for each product with the product name?
App.js
async function contactAPI() {
return await axios({
url: 'https://graphqlexample./api/products',
method: 'post',
data: {
query: `
QUERY GOES HERE
`
}
})
}
async function App() {
let resp = await contactAPI();
return (
<div>
{resp.map(p => (
<div>
<ProductCard productName={p.productName} />
</div>
))}
</div>
);
}
ProductCard.js
function ProductCard(props) {
return (
<div>
<div>{props.productName}</div>
</div>
);
}
Edit: Based on Andy's suggestion, I tried using states and useEffect, but I'm getting two errors. The first one is Error: Objects are not valid as a React child (found: [object Promise]).
and the second one is Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function ponent.
The second error points to const [products, setProducts] = useState([]);
This is my current code:
async function App() {
const [products, setProducts] = useState([]);
useEffect(() => {
async function getData() {
const res = await contactAPI();
setProducts(res.data.data.products);
}
getData();
}, []);
return (
<div>
<div>
{products.map(p => (
<div>
<ProductCard productName={p.productName} />
</div>
))}
</div>
</div>
);
}
Edit 2: Fixed by removing the async
keyword from the original function App()
2 Answers
Reset to default 2Since you're using functional ponents you should implement hooks to 1) get the data, and 2) manage the ponent state. useEffect
to get the data on first render, and useState
to store and manage the data that's returned. You can then map
over that data stored in the state to create the JSX.
const { useEffect, useState } = React;
function App() {
// Initialise the state with an empty array
const [products, setProducts] = useState([]);
// Call `useEffect` with an empty dependency array
// which will ensure it runs only once
useEffect(() => {
// Call the contactAPI function, wait for
// the data and then update the state with the
// product array
async function getData() {
const res = await contactAPI();
setProducts(res.data.data.products);
}
getData();
}, []);
// If the state array is empty show a simple message
if (!data.length) return <div>No data</div>;
// Otherwise `map` over the state and produce the JSX
return (
<div>
{products.map(product => (
<div>
<ProductCard productName={product.productName} />
</div>
))}
</div>
);
}
To display the JSON data in React i have used 2 methods. 1.You can make use of class ponent for fetch it as api. 2.You can import the JSON data file and simply map it.
This is my way of displaying JSON data on React applicatons.
本文标签: javascriptHow to map over a JSON response in ReactStack Overflow
版权声明:本文标题:javascript - How to map over a JSON response in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745446774a2658699.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论