2

I have one API which has title, body, and user-id, and I want to print User Name with the help of another API. So how can I do it? I have listed both APIs in below.

  1. https://jsonplaceholder.typicode.com/posts
  2. https://jsonplaceholder.typicode.com/users/1 // ${id}

getUser(id) {
    let userData = fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
      .then(response => response.json())
      .then((responseJson) => {

        return responseJson.name

      })
      .catch(error => console.log(error)) //to catch the errors if any

    console.log(userData);
    return userData;
}; 
ryeballar
  • 29,658
  • 10
  • 65
  • 74
  • I recommend reading about https://stackoverflow.com/questions/39458201/understanding-javascript-promise-object – ryeballar Jun 28 '19 at 10:59

1 Answers1

3

what you can do is first get the posts and save it inside a variable . then inside a map call other api to get the user data and append the user data in the variable

example

    fetch('https://jsonplaceholder.typicode.com/posts',)
        .then(response => {
            let new_post = [];
            let posts =  response.json() ;
            Promise.all(
                posts.map(item => {
                    fetch('https://jsonplaceholder.typicode.com/users/'+item.userId)
                        .then(res =>{
                            item['user'] = res.json() ;
                            console.log(item)
                            new_post.push(item)
                        })
                })
            )
                .then(() => {
                    this.setState({testing:new_post})
                })
        })

then in your flatlist display username by

            <FlatList
                data={this.state.testing}
                renderItem={({item}) =>(
                        <View>
                            <Text>other</Text>
                            <Text>{item.user.email}</Text>
                        </View>
                    )
                }
            />

OR if your are using axios to get data change code to

axios.get('https://jsonplaceholder.typicode.com/posts',)
.then(response => {})
sachin mathew
  • 1,432
  • 11
  • 19