I'm pulling data from a GraphQL backend. Here is the data that I'm pulling.
{
"data": {
"product": {
"attributes": [
{
"id": "Capacity",
"items": [
{
"id": "256GB",
"displayValue": "256GB"
},
{
"id": "512GB",
"displayValue": "512GB"
}
]
},
{
"id": "With USB 3 ports",
"items": [
{
"id": "Yes",
"displayValue": "Yes"
},
{
"id": "No",
"displayValue": "No"
}
]
},
{
"id": "Touch ID in keyboard",
"items": [
{
"id": "Yes",
"displayValue": "Yes"
},
{
"id": "No",
"displayValue": "No"
}
]
}
]
}
}
}
I'm then iterating through the attributes array and giving unique IDs, _id to differentiate the different items. It turns out that the item that has an ID With USB 3 ports and Touch ID in keyboard always get the same ID. I'm using nanoid.
Here is the code
import { PureComponent } from "react";
import { useParams } from 'react-router-dom';
import { Query } from '@apollo/client/react/components';
import GET_PRODUCT from "../../graphql/getProduct";
import { nanoid } from 'nanoid';
import ProductDetailComponent from "./ProductDetailComponent";
import './ProductDetail.css'
class ProductDetail extends PureComponent {
render() {
const { id } = this.props.params;
const { currency, addToCart, closeCurrencyOverlay } = this.props;
return (
<Query
key="yes"
query={GET_PRODUCT}
variables={{ id }}
fetchPolicy="network-only"
>
{({ loading, data}) => {
if (loading) return null;
let newAttributes = [];
data.product.attributes.map((attribute) => {
attribute.items.map((item) => {
item._id = nanoid(); // <-- Giving the id from here
})
newAttributes.push(attribute)
})
const newData = { ...data, attributes: newAttributes }
return <ProductDetailComponent data={newData} currency={currency} addToCart={addToCart} closeCurrencyOverlay={closeCurrencyOverlay} id={id}/>
}}
</Query>
)
}
}
export default (props) => (
<ProductDetail
{...props}
params={useParams()}
/>
);
I'm just wondering why they always get the same ID.
