简体   繁体   中英

How to get a specific data from fetch api

I am trying to get and show a specific data from api in a <Text> tag in my React Native app. What I'm trying to do is to show the name of second object from that api.

Here is my code:

class HomeSreen extends Component {
 constructor(props) {
   super(props);
   this.state = {
     dataSource: [],
   };
 }
 componentDidMount() {
   const request = new Request('http://jsonplaceholder.typicode.com/users');

   fetch(request)
     .then(response => response.json())
     .then(responseJson => {
       this.setState({
         dataSource: responseJson,
       });
     });
 }
 render() {
   return (
     <View>
       <Text>Home Screen</Text>
       <Text>{this.state.dataSource[1].name}</Text>
     </View>
   );
 }
}

And the API:

[

    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "Sincere@april.biz",
        "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": {
                "lat": "-37.3159",
                "lng": "81.1496"
            }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
        }
    },
    {
        "id": 2,
        "name": "Ervin Howell",
        "username": "Antonette",
        "email": "Shanna@melissa.tv",
        "address": {
            "street": "Victor Plains",
            "suite": "Suite 879",
            "city": "Wisokyburgh",
            "zipcode": "90566-7771",
            "geo": {
                "lat": "-43.9509",
                "lng": "-34.4618"
            }
        },
        "phone": "010-692-6593 x09125",
        "website": "anastasia.net",
        "company": {
            "name": "Deckow-Crist",
            "catchPhrase": "Proactive didactic contingency",
            "bs": "synergize scalable supply-chains"
        }
    },
.
.
.

But I can't get the data I need. Any help would be appreciated

these data requests asynchronously, so when the first render occurs, there is no data returned from the API.

class HomeSreen extends Component {
 constructor(props) {
   super(props);
   this.state = {
     dataSource: [],
   };
 }

 componentDidMount() {
   const request = new Request('http://jsonplaceholder.typicode.com/users');

   fetch(request)
     .then(response => response.json())
     .then(responseJson => {
       this.setState({
         dataSource: responseJson,
       });
     });
 }

 render() {
   return (
     <View>
       <Text>Home Screen</Text>
       {
         this.state.dataSource.length === 0 ?
           <Text>Waiting moment.</Text> :
           <Text>{this.state.dataSource[1].name}</Text>
       }

     </View>
   );
 }
}

Making these changes you can visualize the data you need.

If the problem is that your component isn't updating the that property after the request is complete it is because you are doing a 'shallow merge' on the dataSource Array so React isn't able to detect changes to the data. There are a few ways you can handle it:

  1. Deep merge
fetch(request)
    .then(response => response.json())
    .then(responseJson => {
      this.setState(prevState => {
        return {
          ...prevState.dataSource,
          dataSource: responseJson.map((obj, i)=>{ return {...dataSource[i], ...obj}},
        }
      });
    });

https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action

  1. Pull the name property out to the top-level of you component state
class HomeSreen extends Component {
 constructor(props) {
   super(props);
   this.state = {
     dataSource: [],
     screenTitle
   };
 }
 componentDidMount() {
   const request = new Request('http://jsonplaceholder.typicode.com/users');

   fetch(request)
     .then(response => response.json())
     .then(responseJson => {
       this.setState({
         screenTitle: responseJson[1].name,
       });
     });
 }
 render() {
   return (
     <View>
       <Text>Home Screen</Text>
       <Text>{this.state.screenTitle}</Text>
     </View>
   );
 }
}

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