Sory, I am new here.
I generate Data
object in ASP .Net Core and it is avaliable through GET GetData
:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace ReactImport.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GetPostExampleController : ControllerBase
{
private Data data;
public GetPostExampleController() =>
data = new Data();
[HttpGet("GetData")]
public Data GetData()
{
return data;
}
}
[JsonObject]
public class Data
{
public Data() =>
NestedData = new NestedData();
public int Value { get; set; } = 999;
public NestedData NestedData {get; set;}
}
[JsonObject]
public class NestedData
{
public int NestedValue { get; set; } = 888;
}
}
I can receive this object in my React app and read Data.Value
, but if I try read Data.NestedData.NestedValue
I have an error TypeError: Cannot read property 'nestedValue' of undefined
:
import React, { Component } from 'react';
export class GetPostExample extends Component {
static displayName = GetPostExample.name;
componentDidMount() {
this.ReadData();
}
constructor(props) {
super(props);
this.state = { ReadData: Object, loading: true };
}
async ReadData() {
const response = await fetch('api/GetPostExample/getData');
const data = await response.json();
this.setState({ ReadData: data, loading: false });
}
render() {
return (
<div>
<div>Get:</div>
<div>Data.Value = {this.state.ReadData.value}</div>
{/*TypeError: Cannot read property 'nestedValue' of undefined
*<div>Data.Value = {this.state.ReadData.nestedData.nestedValue}</div>*/}
</div>
);
}
}