简体   繁体   中英

How can I properly read json data from ajax response?

I did something like this:

axios.get(url).then(result => {
   this.setState({
     list: result.data,
   });
})
.catch(e => { 
   console.log("Some error", e);
});

Constructor looks like this:

constructor(props: any) {
   super(props);
   this.state = {
       list: [],
   };
}

I want to put it somewhere and check whether it works:

const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;

but I get uncaught TypeError: cannot read property 'list' of undefined...

It works when I do that this way:

const data: IScheduler = {
      generatedDate: "03.12.2017";
      subjects: [
          ....
      ],
};

But it's not the point. What am I doing wrong? How should I fix it? Can somebody help me?

In your state there is no property fetchedData . You set your list to this.state.list, not to this.state.fetchedData.list . So you need to change your code from:

const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;

to:

const {list}: any = this.state;
const data: IScheduler = list;

It should work. If you really want your first data structure you need to change your default state structure and setState , but nested data structure is not recommended .

axios.get(url).then(result => {
   this.setState({
     fetchedData: {
       list: result.data
     }
   });
})
.catch(e => { 
   console.log("Some error", e);
});

Constructor should looks like this:

constructor(props: any) {
   super(props);
   this.state = {
       fetchedData: {
         list: []
       }
   };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM