D
D
dmitriu2562021-03-11 15:25:15
React
dmitriu256, 2021-03-11 15:25:15

How to reach nested object with data in state?

How to correctly display data from state.user with double nesting?
What I mean is that the user object is stored in the state object, which includes several more objects.
When displaying data on the first level of nesting on the page, everything is displayed perfectly

<h2>Name: {this.state.user.name}</h2>
                <p>UserName: {this.state.user.username}</p>

View nesting causes errors Errors
<p>Srtreet : {this.state.user.address.street}</p>

index.js:1 The above error occurred in the <UsersDetails> component:
Cannot read property 'street' of undefined // в state данные присутствуют


The object has the following form
604a062f11bf2243018339.png

In JavaScript, the view string will successfully display data of any kind of nesting.
console.log(state.user.address.street);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2021-03-11
@dmitriu256

Your object has not yet received data at the time of one of the renders. The fix is ​​simple:

<p>Srtreet: {this.state.user.address && this.state.user.address.street}</p>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question