I have a react project. In this component (AllProductSingleItem.js)
, I destructured the values of match, received as a prop. Now I want to use the id
and personType
value to access a specific value in my data. The id will be the index of the item I’m trying to access and the personType will be value.
The structure of the data looks like this. So for example, I’m trying to access women value like so:
data[id].personType
[
{
“id”:”0”,
“ItemLogo”:”String”
“BrandName”:”String"
“Women”:{an array of object},
“Men”:{an array of object},
“Children”:{an array of object},
“Baby”:{an array of object}
},
{
“id”:”1”,
“ItemLogo”:”String”
“BrandName”:”String"
“Women”:{an array of object},
“Men”:{an array of object},
“Children”:{an array of object},
“Baby”:{an array of object}
}
]
id has a value that comes from match and so does personType.
The problem:
Now the issue is when I try to use the syntax above, it returns undefined. But when I hard code the personType like so data[id].Women
, then I get data back. But I don’t want to hardcode because the value of personType will change based on a user’s interaction.
Here is the react component code so far. It works but it’s not completely dynamic:
import React, { useState,useEffect } from "react";
import { Link } from "react-router-dom";
//import database and component
import data from "../../database/database.json";
function AllProductSingleItem({ match }) {
const [itemArray, setitemArray] = useState([])
const [productId, setproductId] = useState(-1)
const { id, gender, type } = match.params;
const getData = () => {
if (gender === "Women") {
setitemArray(data[id].women)
setproductId(id)
} else if (gender === "Men") {
setitemArray(data[id].men)
setproductId(id)
}
}
return(){
//code
}
}