React Native - how to parse json data and set it in a state object

I have two files (in the same directory):

  • Detail.json
  • base.js

Detail.json is as follows:

[
  {
    "id": 1,
    "name": "A",
  },
  {
    "id": 2,
    "name": "B",
  },
  {
    "id": 3,
    "name": "C",
  }
];

Base.js is as follows:

class Base extends Component {

state = { myDetail: [] }; 

//TODO 1: fetch JSON data from Detail.json and set it to myDetail object

//TODO 2: parse this data from myDetail to display as a single unit (eg: name)

}

I did:

import data from './Detail.json'

console.log(data)gives me my full json object. But when I do this:

this.setState({myDetail: data}); 

& then console.log(myDetail);it shows an empty object in the console.

Can someone tell me how to accomplish the above two tasks. Thank you

+4
source share
1 answer

As Josie said in the comment section, setStateis an asynchronous function, you have to wait for her promise to be resolved.

this.setState({foo: 'bar'}).then(() => {
  console.log(this.state.foo)
});
0

Source: https://habr.com/ru/post/1684910/


All Articles