How can I get all variations
of the product and render them all in a component:
JSON:
[
{
...
},
{
"id": 2,
"title": "chicken burger 2",
"sort": 2,
"img": "http://127.0.0.1:8000/media/categories/unnamed_tyEgUqN.jpg",
"price": 2.0,
"category": {
"id": 1,
"title": "sandwiches",
"img": "http://127.0.0.1:8000/media/categories/original_D3hTuRE.jpg"
},
"description": "chicken burger chicken burger chicken burger chicken burger chicken burger chicken burger chicken burger chicken burger chicken burger chick",
"variations": [
{
"id": 1,
"variation_category": {
"id": 1,
"title": "add ons",
"is_optional": true,
"is_selectable": false
},
"item": "extra cheese",
"price": 0.1
},
{
"id": 2,
"variation_category": {
"id": 1,
"title": "add ons",
"is_optional": true,
"is_selectable": false
},
"item": "double chicken",
"price": 0.6
}
]
}
]
I maped to varioations[0]
and I accessed to the first object only:
function ProductDetailScreen(props) {
//api
const [productsData, setProductsData] = useState([]);
useEffect(() => {
loadProductsData();
}, []);
const loadProductsData = async () => {
const response = await productsApi.getProducts();
setProductsData(response.data);
};
const productId = props.route.params.productId;
const thisProduct = productsData.filter((prod) => prod.id === productId);
const thisVariation = thisProduct.map(v => v.variations[0])
const showVar = thisVariation.map(v => v.item)
return (
...
<MyText>{showVar}</MyText>
...
)
My question is how to get all the variations and render them in MyText, so the output will be:
extra cheese 0.100
double chicken 0.600
Thank you in advance,
You need to do the following:
const variations = thisProduct.map(product => product.variations.map(variation => variation.item))
return variations.map((variation, index) => <MyText key={index}>{variation}</MyText>)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.