React would not access nested state The 2019 Stack Overflow Developer Survey Results Are InWhy would a JavaScript variable start with a dollar sign?How do you access the matched groups in a JavaScript regular expression?Access / process (nested) objects, arrays or JSONWhat is TypeScript and why would I use it in place of JavaScript?How to access the correct `this` inside a callback?Loop inside React JSXWhat is the difference between state and props in React?What do these three dots in React do?Programmatically navigate using react routerWhat is the difference between React Native and React?
Apparent duplicates between Haynes service instructions and MOT
Are there any other methods to apply to solving simultaneous equations?
Resizing object distorts it (Illustrator CC 2018)
Lightning Grid - Columns and Rows?
What is the meaning of the verb "bear" in this context?
What is the closest word meaning "respect for time / mindful"
Protecting Dualbooting Windows from dangerous code (like rm -rf)
Does a dangling wire really electrocute me if I'm standing in water?
Why is the maximum length of OpenWrt’s root password 8 characters?
How to save as into a customized destination on macOS?
Can one be advised by a professor who is very far away?
Is bread bad for ducks?
Earliest use of the term "Galois extension"?
Do these rules for Critical Successes and Critical Failures seem Fair?
Button changing it's text & action. Good or terrible?
What is the motivation for a law requiring 2 parties to consent for recording a conversation
Output the Arecibo Message
How to answer pointed "are you quitting" questioning when I don't want them to suspect
Why isn't airport relocation done gradually?
Can you compress metal and what would be the consequences?
Why was M87 targetted for the Event Horizon Telescope instead of Sagittarius A*?
Multiply Two Integer Polynomials
Aging parents with no investments
Is this app Icon Browser Safe/Legit?
React would not access nested state
The 2019 Stack Overflow Developer Survey Results Are InWhy would a JavaScript variable start with a dollar sign?How do you access the matched groups in a JavaScript regular expression?Access / process (nested) objects, arrays or JSONWhat is TypeScript and why would I use it in place of JavaScript?How to access the correct `this` inside a callback?Loop inside React JSXWhat is the difference between state and props in React?What do these three dots in React do?Programmatically navigate using react routerWhat is the difference between React Native and React?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have set React state to data from an API
this.setState(loan: response.data)
response.data is a nested object
application:
amount: 20,
interest: 10,
guarantor:
firstName: "John",
lastName: "Doe"
,
userId: "123"
Normally inside the render function i can access
<p>this.state.loan.userId</p>
<p>this.state.loan.application.amount</p>
<p>this.state.loan.application.guarantor.firstName</p>
Now I can only access the first child of the loan. Except i practically set the state for each individual item in the object. Note console.log(this.state.loan.application.guarantor)
works fine.
This is the API call
fetch(`http://localhost:8000/api/v1/loans/$this.state.id`)
.then(res =>
return res.json();
).then(response =>
this.setState(loan: response.data);
)
.catch(err => console.log(err));
const loan = this.state;
<div className="col-md-4">
<h5 className="title">Full Name</h5>
<p>loan.fullName</p>
<h5 className="title mt-3">Account Number</h5>
<p>loan.accountNumber</p>
<h5 className="title mt-3">Phone Number</h5>
<p>Phone Number</p>
</div>
<div className="col-md-4">
<h5 className="title">Loan Amount</h5>
<p>
(loan.application.amount).toLocaleString("en-NG",
style: "currency",
currency: "NGN"
)
</p>
<h5 className="title mt-3">Interest Rate</h5>
<p>loan.interestRate%</p>
<h5 className="title mt-3">Duration</h5>
<p>loan.duration Months</p>
</div>
The response from API call
"application":
"guarantor1":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"occupation": "Accountant",
"netIncome": "50000",
"placeOfWork": "Dreamworld",
"employer": "Ayebakuro Ombu",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "10101010101",
"phoneNumber": "010101010101"
,
"guarantor2":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "B48 Copa Cobana Estate, Wumba, Lokogoma",
"occupation": "business man",
"netIncome": "500000",
"placeOfWork": "Dreamworld",
"employer": "SafeScrow Tech",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "0101010101",
"phoneNumber": "0101010101"
,
"mode":
"name": "DreamWorld Savings And Loans Ltd",
"address": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"netIncome": "50000"
,
"bankDetails":
"bank": "Parallex Bank",
"accountNumber": "0101010101",
"bvn": "0101010101"
,
"amount": 200000,
"number": "25642",
"date": "2019-03-22T02:37:58.069Z",
"purpose": "For debt payment"
,
"approval":
"amount": 0,
"status": "Pending"
,
"issue":
"status": false
,
"payment":
"schedule": [],
"completed": false
,
"_id": "5c944a86abf7ea09c40301e5",
"accountNumber": "1000000002",
"fullName": "Ayebakuro Ombu",
"type": "Business",
"duration": 5,
"interestRate": 10,
"__v": 0
The error: LoanPage.js:61 Uncaught TypeError: Cannot read property 'amount' of undefined
at LoanPage.render (LoanPage.js:61)
Logging this.state.loan.application.amount logs correctly
javascript reactjs
|
show 5 more comments
I have set React state to data from an API
this.setState(loan: response.data)
response.data is a nested object
application:
amount: 20,
interest: 10,
guarantor:
firstName: "John",
lastName: "Doe"
,
userId: "123"
Normally inside the render function i can access
<p>this.state.loan.userId</p>
<p>this.state.loan.application.amount</p>
<p>this.state.loan.application.guarantor.firstName</p>
Now I can only access the first child of the loan. Except i practically set the state for each individual item in the object. Note console.log(this.state.loan.application.guarantor)
works fine.
This is the API call
fetch(`http://localhost:8000/api/v1/loans/$this.state.id`)
.then(res =>
return res.json();
).then(response =>
this.setState(loan: response.data);
)
.catch(err => console.log(err));
const loan = this.state;
<div className="col-md-4">
<h5 className="title">Full Name</h5>
<p>loan.fullName</p>
<h5 className="title mt-3">Account Number</h5>
<p>loan.accountNumber</p>
<h5 className="title mt-3">Phone Number</h5>
<p>Phone Number</p>
</div>
<div className="col-md-4">
<h5 className="title">Loan Amount</h5>
<p>
(loan.application.amount).toLocaleString("en-NG",
style: "currency",
currency: "NGN"
)
</p>
<h5 className="title mt-3">Interest Rate</h5>
<p>loan.interestRate%</p>
<h5 className="title mt-3">Duration</h5>
<p>loan.duration Months</p>
</div>
The response from API call
"application":
"guarantor1":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"occupation": "Accountant",
"netIncome": "50000",
"placeOfWork": "Dreamworld",
"employer": "Ayebakuro Ombu",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "10101010101",
"phoneNumber": "010101010101"
,
"guarantor2":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "B48 Copa Cobana Estate, Wumba, Lokogoma",
"occupation": "business man",
"netIncome": "500000",
"placeOfWork": "Dreamworld",
"employer": "SafeScrow Tech",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "0101010101",
"phoneNumber": "0101010101"
,
"mode":
"name": "DreamWorld Savings And Loans Ltd",
"address": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"netIncome": "50000"
,
"bankDetails":
"bank": "Parallex Bank",
"accountNumber": "0101010101",
"bvn": "0101010101"
,
"amount": 200000,
"number": "25642",
"date": "2019-03-22T02:37:58.069Z",
"purpose": "For debt payment"
,
"approval":
"amount": 0,
"status": "Pending"
,
"issue":
"status": false
,
"payment":
"schedule": [],
"completed": false
,
"_id": "5c944a86abf7ea09c40301e5",
"accountNumber": "1000000002",
"fullName": "Ayebakuro Ombu",
"type": "Business",
"duration": 5,
"interestRate": 10,
"__v": 0
The error: LoanPage.js:61 Uncaught TypeError: Cannot read property 'amount' of undefined
at LoanPage.render (LoanPage.js:61)
Logging this.state.loan.application.amount logs correctly
javascript reactjs
You need to add more about your code, like the format ofresponse.data
, and where did you put the console?
– bird
Mar 22 at 3:55
it is strange that you refer toconsole.log(this.state.user.application.guarantor)
. You wrotethis.state.user
instead ofthis.state.loan
. Could it be possible that thethis.setState(loan: response.data)
expression is not exactly like that in the code?
– Carlos Lombardi
Mar 22 at 4:00
You will have to provide more code for anyone to help you. Please consider sharing your whole component.
– Dehan de Croos
Mar 22 at 4:55
Is loan an array of objects?
– Jibin Joseph
Mar 22 at 4:56
What's otherwise the error that you getting when you access nested objects in load?
– Jibin Joseph
Mar 22 at 4:57
|
show 5 more comments
I have set React state to data from an API
this.setState(loan: response.data)
response.data is a nested object
application:
amount: 20,
interest: 10,
guarantor:
firstName: "John",
lastName: "Doe"
,
userId: "123"
Normally inside the render function i can access
<p>this.state.loan.userId</p>
<p>this.state.loan.application.amount</p>
<p>this.state.loan.application.guarantor.firstName</p>
Now I can only access the first child of the loan. Except i practically set the state for each individual item in the object. Note console.log(this.state.loan.application.guarantor)
works fine.
This is the API call
fetch(`http://localhost:8000/api/v1/loans/$this.state.id`)
.then(res =>
return res.json();
).then(response =>
this.setState(loan: response.data);
)
.catch(err => console.log(err));
const loan = this.state;
<div className="col-md-4">
<h5 className="title">Full Name</h5>
<p>loan.fullName</p>
<h5 className="title mt-3">Account Number</h5>
<p>loan.accountNumber</p>
<h5 className="title mt-3">Phone Number</h5>
<p>Phone Number</p>
</div>
<div className="col-md-4">
<h5 className="title">Loan Amount</h5>
<p>
(loan.application.amount).toLocaleString("en-NG",
style: "currency",
currency: "NGN"
)
</p>
<h5 className="title mt-3">Interest Rate</h5>
<p>loan.interestRate%</p>
<h5 className="title mt-3">Duration</h5>
<p>loan.duration Months</p>
</div>
The response from API call
"application":
"guarantor1":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"occupation": "Accountant",
"netIncome": "50000",
"placeOfWork": "Dreamworld",
"employer": "Ayebakuro Ombu",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "10101010101",
"phoneNumber": "010101010101"
,
"guarantor2":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "B48 Copa Cobana Estate, Wumba, Lokogoma",
"occupation": "business man",
"netIncome": "500000",
"placeOfWork": "Dreamworld",
"employer": "SafeScrow Tech",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "0101010101",
"phoneNumber": "0101010101"
,
"mode":
"name": "DreamWorld Savings And Loans Ltd",
"address": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"netIncome": "50000"
,
"bankDetails":
"bank": "Parallex Bank",
"accountNumber": "0101010101",
"bvn": "0101010101"
,
"amount": 200000,
"number": "25642",
"date": "2019-03-22T02:37:58.069Z",
"purpose": "For debt payment"
,
"approval":
"amount": 0,
"status": "Pending"
,
"issue":
"status": false
,
"payment":
"schedule": [],
"completed": false
,
"_id": "5c944a86abf7ea09c40301e5",
"accountNumber": "1000000002",
"fullName": "Ayebakuro Ombu",
"type": "Business",
"duration": 5,
"interestRate": 10,
"__v": 0
The error: LoanPage.js:61 Uncaught TypeError: Cannot read property 'amount' of undefined
at LoanPage.render (LoanPage.js:61)
Logging this.state.loan.application.amount logs correctly
javascript reactjs
I have set React state to data from an API
this.setState(loan: response.data)
response.data is a nested object
application:
amount: 20,
interest: 10,
guarantor:
firstName: "John",
lastName: "Doe"
,
userId: "123"
Normally inside the render function i can access
<p>this.state.loan.userId</p>
<p>this.state.loan.application.amount</p>
<p>this.state.loan.application.guarantor.firstName</p>
Now I can only access the first child of the loan. Except i practically set the state for each individual item in the object. Note console.log(this.state.loan.application.guarantor)
works fine.
This is the API call
fetch(`http://localhost:8000/api/v1/loans/$this.state.id`)
.then(res =>
return res.json();
).then(response =>
this.setState(loan: response.data);
)
.catch(err => console.log(err));
const loan = this.state;
<div className="col-md-4">
<h5 className="title">Full Name</h5>
<p>loan.fullName</p>
<h5 className="title mt-3">Account Number</h5>
<p>loan.accountNumber</p>
<h5 className="title mt-3">Phone Number</h5>
<p>Phone Number</p>
</div>
<div className="col-md-4">
<h5 className="title">Loan Amount</h5>
<p>
(loan.application.amount).toLocaleString("en-NG",
style: "currency",
currency: "NGN"
)
</p>
<h5 className="title mt-3">Interest Rate</h5>
<p>loan.interestRate%</p>
<h5 className="title mt-3">Duration</h5>
<p>loan.duration Months</p>
</div>
The response from API call
"application":
"guarantor1":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"occupation": "Accountant",
"netIncome": "50000",
"placeOfWork": "Dreamworld",
"employer": "Ayebakuro Ombu",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "10101010101",
"phoneNumber": "010101010101"
,
"guarantor2":
"fullName": "Ayebakuro Ombu",
"residentialAddress": "B48 Copa Cobana Estate, Wumba, Lokogoma",
"occupation": "business man",
"netIncome": "500000",
"placeOfWork": "Dreamworld",
"employer": "SafeScrow Tech",
"relationship": "Employer",
"bvn": "0101010101",
"bank": "GTBank",
"accountNumber": "0101010101",
"phoneNumber": "0101010101"
,
"mode":
"name": "DreamWorld Savings And Loans Ltd",
"address": "30 Udengs Eradiri Avenue Off Azikoro Village Road",
"netIncome": "50000"
,
"bankDetails":
"bank": "Parallex Bank",
"accountNumber": "0101010101",
"bvn": "0101010101"
,
"amount": 200000,
"number": "25642",
"date": "2019-03-22T02:37:58.069Z",
"purpose": "For debt payment"
,
"approval":
"amount": 0,
"status": "Pending"
,
"issue":
"status": false
,
"payment":
"schedule": [],
"completed": false
,
"_id": "5c944a86abf7ea09c40301e5",
"accountNumber": "1000000002",
"fullName": "Ayebakuro Ombu",
"type": "Business",
"duration": 5,
"interestRate": 10,
"__v": 0
The error: LoanPage.js:61 Uncaught TypeError: Cannot read property 'amount' of undefined
at LoanPage.render (LoanPage.js:61)
Logging this.state.loan.application.amount logs correctly
javascript reactjs
javascript reactjs
edited Mar 22 at 7:31
Jotakun
178110
178110
asked Mar 22 at 3:49
Kuro OmbuKuro Ombu
198
198
You need to add more about your code, like the format ofresponse.data
, and where did you put the console?
– bird
Mar 22 at 3:55
it is strange that you refer toconsole.log(this.state.user.application.guarantor)
. You wrotethis.state.user
instead ofthis.state.loan
. Could it be possible that thethis.setState(loan: response.data)
expression is not exactly like that in the code?
– Carlos Lombardi
Mar 22 at 4:00
You will have to provide more code for anyone to help you. Please consider sharing your whole component.
– Dehan de Croos
Mar 22 at 4:55
Is loan an array of objects?
– Jibin Joseph
Mar 22 at 4:56
What's otherwise the error that you getting when you access nested objects in load?
– Jibin Joseph
Mar 22 at 4:57
|
show 5 more comments
You need to add more about your code, like the format ofresponse.data
, and where did you put the console?
– bird
Mar 22 at 3:55
it is strange that you refer toconsole.log(this.state.user.application.guarantor)
. You wrotethis.state.user
instead ofthis.state.loan
. Could it be possible that thethis.setState(loan: response.data)
expression is not exactly like that in the code?
– Carlos Lombardi
Mar 22 at 4:00
You will have to provide more code for anyone to help you. Please consider sharing your whole component.
– Dehan de Croos
Mar 22 at 4:55
Is loan an array of objects?
– Jibin Joseph
Mar 22 at 4:56
What's otherwise the error that you getting when you access nested objects in load?
– Jibin Joseph
Mar 22 at 4:57
You need to add more about your code, like the format of
response.data
, and where did you put the console?– bird
Mar 22 at 3:55
You need to add more about your code, like the format of
response.data
, and where did you put the console?– bird
Mar 22 at 3:55
it is strange that you refer to
console.log(this.state.user.application.guarantor)
. You wrote this.state.user
instead of this.state.loan
. Could it be possible that the this.setState(loan: response.data)
expression is not exactly like that in the code?– Carlos Lombardi
Mar 22 at 4:00
it is strange that you refer to
console.log(this.state.user.application.guarantor)
. You wrote this.state.user
instead of this.state.loan
. Could it be possible that the this.setState(loan: response.data)
expression is not exactly like that in the code?– Carlos Lombardi
Mar 22 at 4:00
You will have to provide more code for anyone to help you. Please consider sharing your whole component.
– Dehan de Croos
Mar 22 at 4:55
You will have to provide more code for anyone to help you. Please consider sharing your whole component.
– Dehan de Croos
Mar 22 at 4:55
Is loan an array of objects?
– Jibin Joseph
Mar 22 at 4:56
Is loan an array of objects?
– Jibin Joseph
Mar 22 at 4:56
What's otherwise the error that you getting when you access nested objects in load?
– Jibin Joseph
Mar 22 at 4:57
What's otherwise the error that you getting when you access nested objects in load?
– Jibin Joseph
Mar 22 at 4:57
|
show 5 more comments
1 Answer
1
active
oldest
votes
When a component is rendered (like the following code), React calls the render
method of corresponding component immediately.
ReactDom.render(<LoanPage />, element);
Event if you were to execute a asynchronous fetch
in constructor, or componentWillMount
method, that wouldn't prevent the React system from executing render.
This is how you should approach this problem. In constructor / componentWillMount, you should set this.state.loading = true
, and then fire the fetch call. In the .then
part of fetch call, setState to clear the loading flag like this:
this.setState(
loading: false,
loan: response.data
);
The render
method of LoanPage can now benefit from the knowledge of 'fetch call in progress' like this:
render()
if(this.state.loading)
return (<h3>Loading...</h3>);
return (
<div> Loan amount is this.state.loan.application.amount </div>
);
You can change the first part of render (in if condition) to display a spinner or some equivalent. You should change the second part to render everything that you are rendering now.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292631%2freact-would-not-access-nested-state%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
When a component is rendered (like the following code), React calls the render
method of corresponding component immediately.
ReactDom.render(<LoanPage />, element);
Event if you were to execute a asynchronous fetch
in constructor, or componentWillMount
method, that wouldn't prevent the React system from executing render.
This is how you should approach this problem. In constructor / componentWillMount, you should set this.state.loading = true
, and then fire the fetch call. In the .then
part of fetch call, setState to clear the loading flag like this:
this.setState(
loading: false,
loan: response.data
);
The render
method of LoanPage can now benefit from the knowledge of 'fetch call in progress' like this:
render()
if(this.state.loading)
return (<h3>Loading...</h3>);
return (
<div> Loan amount is this.state.loan.application.amount </div>
);
You can change the first part of render (in if condition) to display a spinner or some equivalent. You should change the second part to render everything that you are rendering now.
add a comment |
When a component is rendered (like the following code), React calls the render
method of corresponding component immediately.
ReactDom.render(<LoanPage />, element);
Event if you were to execute a asynchronous fetch
in constructor, or componentWillMount
method, that wouldn't prevent the React system from executing render.
This is how you should approach this problem. In constructor / componentWillMount, you should set this.state.loading = true
, and then fire the fetch call. In the .then
part of fetch call, setState to clear the loading flag like this:
this.setState(
loading: false,
loan: response.data
);
The render
method of LoanPage can now benefit from the knowledge of 'fetch call in progress' like this:
render()
if(this.state.loading)
return (<h3>Loading...</h3>);
return (
<div> Loan amount is this.state.loan.application.amount </div>
);
You can change the first part of render (in if condition) to display a spinner or some equivalent. You should change the second part to render everything that you are rendering now.
add a comment |
When a component is rendered (like the following code), React calls the render
method of corresponding component immediately.
ReactDom.render(<LoanPage />, element);
Event if you were to execute a asynchronous fetch
in constructor, or componentWillMount
method, that wouldn't prevent the React system from executing render.
This is how you should approach this problem. In constructor / componentWillMount, you should set this.state.loading = true
, and then fire the fetch call. In the .then
part of fetch call, setState to clear the loading flag like this:
this.setState(
loading: false,
loan: response.data
);
The render
method of LoanPage can now benefit from the knowledge of 'fetch call in progress' like this:
render()
if(this.state.loading)
return (<h3>Loading...</h3>);
return (
<div> Loan amount is this.state.loan.application.amount </div>
);
You can change the first part of render (in if condition) to display a spinner or some equivalent. You should change the second part to render everything that you are rendering now.
When a component is rendered (like the following code), React calls the render
method of corresponding component immediately.
ReactDom.render(<LoanPage />, element);
Event if you were to execute a asynchronous fetch
in constructor, or componentWillMount
method, that wouldn't prevent the React system from executing render.
This is how you should approach this problem. In constructor / componentWillMount, you should set this.state.loading = true
, and then fire the fetch call. In the .then
part of fetch call, setState to clear the loading flag like this:
this.setState(
loading: false,
loan: response.data
);
The render
method of LoanPage can now benefit from the knowledge of 'fetch call in progress' like this:
render()
if(this.state.loading)
return (<h3>Loading...</h3>);
return (
<div> Loan amount is this.state.loan.application.amount </div>
);
You can change the first part of render (in if condition) to display a spinner or some equivalent. You should change the second part to render everything that you are rendering now.
answered Mar 22 at 6:56
elem4thelem4th
80157
80157
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292631%2freact-would-not-access-nested-state%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You need to add more about your code, like the format of
response.data
, and where did you put the console?– bird
Mar 22 at 3:55
it is strange that you refer to
console.log(this.state.user.application.guarantor)
. You wrotethis.state.user
instead ofthis.state.loan
. Could it be possible that thethis.setState(loan: response.data)
expression is not exactly like that in the code?– Carlos Lombardi
Mar 22 at 4:00
You will have to provide more code for anyone to help you. Please consider sharing your whole component.
– Dehan de Croos
Mar 22 at 4:55
Is loan an array of objects?
– Jibin Joseph
Mar 22 at 4:56
What's otherwise the error that you getting when you access nested objects in load?
– Jibin Joseph
Mar 22 at 4:57