I’m using an useEffect to get an object that has another object inside it, for example:
estoque:
{
'param1': 'a',
'param2': 'b',
'param3': {
'logradouro': 'a2'
'bairro': 'b2'
}
}
The page already loads rendering the infos from estoque.param1 and estoque.param2.
If I try to render the info inside Param3 when the page has ALREADY loaded, it works fine.
But, if I refresh the page, or try to load it with the Param3’s ‘logradouro’ or ‘bairro’ already trying to be rendered, I get the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'logradouro')
at EstoquePage (EstoquePage.jsx:67:35)
at renderWithHooks (chunk-YAPSZIQJ.js?v=78d453af:12169:26)
at mountIndeterminateComponent (chunk-YAPSZIQJ.js?v=78d453af:14919:21)
at beginWork (chunk-YAPSZIQJ.js?v=78d453af:15900:22)
at beginWork$1 (chunk-YAPSZIQJ.js?v=78d453af:19747:22)
at performUnitOfWork (chunk-YAPSZIQJ.js?v=78d453af:19192:20)
at workLoopSync (chunk-YAPSZIQJ.js?v=78d453af:19131:13)
at renderRootSync (chunk-YAPSZIQJ.js?v=78d453af:19110:15)
at recoverFromConcurrentError (chunk-YAPSZIQJ.js?v=78d453af:18730:28)
at performConcurrentWorkOnRoot (chunk-YAPSZIQJ.js?v=78d453af:18678:30)`
-The error points to line 67:35, that’s where I’m trying to render {estoque.param3.logradouro}-
For info, my useEffect is as follows:
useEffect(() => {
async function fetchStore() {
try {
const storeResponse = await fetch(`http://localhost:8080/dbtable/${id}`)
if(!storeResponse.ok){
throw new Error('Couldnt fetch any object.')
}
const dataStore = await storeResponse.json();
setStore(dataStore);
} catch (e) {
console.error(e)
}
}
fetchStore();
}, [])
Not sure what to do here, would appreciate if someone could help 🙂
>Solution :
The error you are receiving is when your component first renders estoque.param3 is undefined so you need to add conditional rendering so it will not attempt to render until after it gets the data.
{estoque.param3 && (
<div>
<p>Logradouro: {estoque.param3.logradouro}</p>
<p>Bairro: {estoque.param3.bairro}</p>
</div>
)}