I'm using React js and Context. I have a "complex" object like below, which I want to make it available in childs views using Context:
{
carSelected:
{
"carEntityId": 6,
"mileage": 100000,
"immatriculationDate": "2020-05-01T00:00:00",
"vin": "VIN-cF95ew0cp0ZhxE=w",
"licencePlate": "GR-999-RT"
"carModel": {
"carModelId": 2,
"brand": "Fiat",
"model": "Tipo",
"motor": "1.7D",
...
}
}
carsAvailable: [
{
<list of car like car selected>
}
]
}
In App.js, I'm setting state for that:
this.setCarEntity = (carSelected, carsAvailable) => {
console.info("[setCarEntity] Car selected: " + JSON.stringify(carSelected, null, 4));
this.setState({
carEntity: {
carSelected: carSelected,
carsAvailable: carsAvailable,
}
})
}
And then in App render:
<CarEntityContext.Provider value={this.state.carEntity}>
<CarEntityHome/>
</CarEntityContext.Provider>
Looks fine to me.
In CarEntityHome, I'm trying to access to the object. I can access values to primary key, this is working:
<CarEntityContext.Consumer>
{valueCE =>
(valueCE !== null && valueCE.carSelected !== null) &&
<p> Car selected | id {valueCE.carSelected.carEntityId} / {valueCE.carSelected.mileage} km <br/>
</p>
}
</CarEntityContext.Consumer>
But, I can't access to the object embedded in my "carSelected" object:
{valueCE.carSelected.carModel.carModelId}
This is failing, saying:
TypeError: Cannot read property 'carModelId' of undefined
Same goes for all property in "carModel" subobject.
But, if I display the object to check if it's correctly populated, it is actually the case:
<pre>{JSON.stringify(valueCE.carSelected, null, 2) }</pre>
Give:
{
"carEntityId": 6,
"mileage": 100000,
"immatriculationDate": "2020-05-01T00:00:00",
"vin": "VIN-cF95ew0cp0ZhxE=w",
"licencePlate": "GR-999-RT",
"carModel": {
"carModelId": 2,
"brand": "Fiat",
"model": "Tipo",
"motor": "1.7D",
"horsePower": 57,
"kwPower": 40,
"fiscalPower": 4,
"energy": "petrol",
"finition": "Pop",
"maintenancePlan": null
},
"userDB": null
}
So I'm very confused here. My object is properly populated. But is there a limitation in Context to access to embedded / complex object ? Am I missing something obvious here ? Could not find an answer in official doc, could be a bug ?
Thanks in advance for your answers.