I'm using GraphQL API for my react native project. I would like to know some questions about GraphQL since I'm beginner of using it.
I found two methods of fetching data from GraphQL to react native application
- Using ApolloProvider to Fetch data
- Using Fetch Method ( Same like REST API's )
I want to know what is the correct way of doing GraphQL requests with react native application.
Once I use ApolloProvider and GraphQL Tags the response is in between Query Tags. But once I use normal fetch It will act as normal HTTP Request.
Normal Fetch Function to get GraphQL Data
fetch('http://snowtooth.moonhighway.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: 'query { allLifts { id name status } }',
}),
})
.then(response => response.json())
.then(responseText => {
this.setState({users_data: responseText.data.allLifts});
})
.catch(error => {});
This is the standard GraphQL using ApolloProvider and Tags
const query = gql`
query {
players {
position
name
team
jerseyNumber
wonSuperBowl
}
}
`;
//Define your component
class PlayersList extends PureComponent {
//Define your method for rendering each individual item
_renderItem({item}) {
//Return the UI
//It will return the text green or red depending if that player won a super bowl or not.
return (
<TouchableOpacity style={styles.itemContainer}>
<Text style={styles.itemText}>Position: {item.position}</Text>
<Text style={styles.itemText}>Name: {item.name}</Text>
<Text style={styles.itemText}>Team: {item.team}</Text>
<Text style={styles.itemText}>Jersey Number: {item.jerseyNumber}</Text>
<Text style={[styles.itemText, item.wonSuperBowl ? styles.wonSuperBowlText : styles.errorText]}>
Won Superbowl: {item.wonSuperBowl ? 'YES' : 'NO'}
</Text>
</TouchableOpacity>
);
}
render() {
//render your ui with the styles set for each ui element.
return (
<ScrollView style={styles.container}>
{/*Can use an array to override styles for your UI elements.*/}
<Text style={[styles.itemText, styles.headerText]}>Top 25 NFL Players List</Text>
<Query query={query}>
{/* The props.children of the Query will be a callback with a response, and error parameter. */}
{(response, error) => {
if(error) {
console.log('Response Error-------', error);
return <Text style={styles.errorText}>{error}</Text>
}
//If the response is done, then will return the FlatList
if(response) {
console.log('response-data-------------', response);
//Return the FlatList if there is not an error.
return <FlatList
data={response.data.players}
renderItem={(item) => this._renderItem(item)}
/>;
}
}}
</Query>
</ScrollView>
);
}
}
I would like to know what is the best way of fetching data using GraphQL. If I do normal fetch what are the limitations ?